Pengenalan
Untuk memudahkan pelaksanaan klien SOAP, Java menawarkan SAAJ (SOAP dengan Lampiran rangka kerja API untuk Java). SAAJ membolehkan manipulasi langsung permintaan SOAP dan mesej tindak balas. Rangka kerja ini adalah sebahagian daripada JSE dalam versi sehingga 1.6 dan 11 dan seterusnya.
Contoh SOAP Client Menggunakan SAAJ
Coretan kod Java berikut mempamerkan panggilan perkhidmatan web SOAP yang berfungsi menggunakan SAAJ:
import javax.xml.soap.*; public class SOAPClientSAAJ { // SAAJ - SOAP Client Testing public static void main(String[] args) { String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx"; String soapAction = "http://www.webserviceX.NET/GetInfoByCity"; callSoapWebService(soapEndpointUrl, soapAction); } private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException { String myNamespace = "myNamespace"; String myNamespaceURI = "http://www.webserviceX.NET"; SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI); SOAPBody soapBody = envelope.getBody(); SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace); SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace); soapBodyElem1.addTextNode("New York"); } private static void callSoapWebService(String soapEndpointUrl, String soapAction) { try { SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance(); SOAPConnection soapConnection = soapConnectionFactory.createConnection(); SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl); System.out.println("Response SOAP Message:"); soapResponse.writeTo(System.out); System.out.println(); soapConnection.close(); } catch (Exception e) { System.err.println("Error occurred while sending SOAP Request to Server! Make sure you have the correct endpoint URL and SOAPAction!"); e.printStackTrace(); } } private static SOAPMessage createSOAPRequest(String soapAction) throws Exception { MessageFactory messageFactory = MessageFactory.newInstance(); SOAPMessage soapMessage = messageFactory.createMessage(); createSoapEnvelope(soapMessage); MimeHeaders headers = soapMessage.getMimeHeaders(); headers.addHeader("SOAPAction", soapAction); soapMessage.saveChanges(); System.out.println("Request SOAP Message:"); soapMessage.writeTo(System.out); System.out.println("\n"); return soapMessage; } }
Atas ialah kandungan terperinci Bagaimanakah saya boleh menggunakan SAAJ untuk melaksanakan klien SOAP di Jawa?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!