要用Java实现简单的SOAP客户端,可以使用SAAJ框架(JSE 1.6及更高版本附带):
带有Java附件API的SOAP(SAAJ)主要用于直接处理任何Web Service API幕后发生的SOAP请求/响应消息。它允许开发人员直接发送和接收肥皂消息,而不是使用JAX-WS。
参见下面使用SAAJ进行SOAP Web服务调用的工作示例(运行它!)。它称为此Web服务。
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 { SOAPPart soapPart = soapMessage.getSOAPPart(); String myNamespace = "myNamespace"; String myNamespaceURI = "http://www.webserviceX.NET"; // SOAP Envelope SOAPEnvelope envelope = soapPart.getEnvelope(); envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI); // SOAP Body 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); System.out.println(); soapConnection.close(); } catch (Exception e) { System.err.println("nError occurred while sending SOAP Request to Server!nMake sure you have the correct endpoint URL and SOAPAction!n"); 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; }}


