使用 SAAJ 框架可以简化在 Java 中实现 SOAP 客户端。这个多功能框架使开发人员能够直接处理 SOAP 请求和响应消息,超越了 JAX-WS 的功能。
为了说明 SAAJ 的功能,请考虑以下 Web 服务调用:
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 { SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance(); SOAPConnection soapConnection = soapConnectionFactory.createConnection(); SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl); soapResponse.writeTo(System.out); System.out.println(); soapConnection.close(); } catch (Exception e) { System.err.println("Error sending SOAP Request. Ensure 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(); soapMessage.writeTo(System.out); System.out.println(); return soapMessage; } }
这个综合示例演示了使用 SAAJ 的 SOAP Web 服务调用。修改参数以满足您特定的 Web 服务要求,并记住更改 createSoapEnvelope() 方法的内容以自定义 SOAP 信封的内容。
以上是如何使用 SAAJ 在 Java 中实现 SOAP 客户端?的详细内容。更多信息请关注PHP中文网其他相关文章!