Melaksanakan Klien SOAP Bekerja Menggunakan SAAJ
Di Java, Simple Object Access Protocol (SOAP) boleh dilaksanakan menggunakan SOAP with Attachments API untuk rangka kerja Java (SAAJ). Rangka kerja ini membolehkan pembangun mengendalikan secara langsung mesej SOAP, dan bukannya bergantung pada API perkhidmatan web pihak ketiga.
Mencipta Klien SOAP dengan SAAJ
Di bawah ialah contoh pelanggan SOAP yang berfungsi dilaksanakan menggunakan SAAJ:
import javax.xml.soap.*; public class SOAPClientSAAJ { 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 { SOAPPart soapPart = soapMessage.getSOAPPart(); String myNamespace = "myNamespace"; String myNamespaceURI = "http://www.webserviceX.NET"; 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 { // Create SOAP connection SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance(); SOAPConnection soapConnection = soapConnectionFactory.createConnection(); // Send SOAP message to SOAP server SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl); // Print the SOAP response System.out.println("Response SOAP Message:"); soapResponse.writeTo(System.out); soapConnection.close(); } catch (Exception e) { System.err.println("Error occurred while sending SOAP Request to Server!"); 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(); return soapMessage; } }
Atas ialah kandungan terperinci Bagaimana untuk Membina Klien SOAP Fungsional dengan SAAJ di Java?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!