工作肥皂客户端的例子

我试图find一个简单的(哈)SOAP例如与工作服务的JAVA,任何我似乎发现不工作。

我从这个例子中尝试了这个,但是它只是不工作,它要求我把一个正斜杠,但它在那里,没有任何事情发生。

那么有谁知道任何SOAP示例链接,我可以下载/请求和混乱?

谢谢你的帮助。

要在Java中实现简单的SOAP客户端,可以使用SAAJ框架(它随JSE 1.6及更高版本一起提供):

附带API的Java(SAAJ) SOAP主要用于直接处理任何Web Service API中幕后发生的SOAP请求/响应消息。 它允许开发人员直接发送和接收SOAP消息,而不是使用JAX-WS。

使用SAAJ查看SOAP Web服务调用的一个工作示例(运行它!)。 它调用这个Web服务 。

import javax.xml.soap.*; public class SOAPClientSAAJ { // SAAJ - SOAP Client Testing public static void main(String args[]) { /* The example below requests from the Web Service at: http://www.webservicex.net/uszip.asmx?op=GetInfoByCity To call other WS, change the parameters below, which are: - the SOAP Endpoint URL (that is, where the service is responding from) - the SOAP Action Also change the contents of the method createSoapEnvelope() in this class. It constructs the inner part of the SOAP envelope that is actually sent. */ 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); /* Constructed SOAP Request Message: <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="http://www.webserviceX.NET"> <SOAP-ENV:Header/> <SOAP-ENV:Body> <myNamespace:GetInfoByCity> <myNamespace:USCity>New York</myNamespace:USCity> </myNamespace:GetInfoByCity> </SOAP-ENV:Body> </SOAP-ENV:Envelope> */ // 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(); /* Print the request message, just for debugging purposes */ System.out.println("Request SOAP Message:"); soapMessage.writeTo(System.out); System.out.println("\n"); return soapMessage; } } 

是的,如果您可以获取任何WSDL文件,那么您可以使用SoapUI创build该服务的模拟服务,并完成unit testing请求。 我创build了一个可以尝试的例子(使用Maven) 。

另外, 这里是一个有人发布的免费web服务的巨大列表。

acdcjunior的反应很棒,我只是用下一个代码展开他的解释,在那里你可以看到如何迭代XML元素。

 public class SOAPClientSAAJ { public static void main(String args[]) throws Exception { // Create SOAP Connection SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance(); SOAPConnection soapConnection = soapConnectionFactory.createConnection(); // Send SOAP Message to SOAP Server String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx"; SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url); SOAPPart soapPart=soapResponse.getSOAPPart(); // SOAP Envelope SOAPEnvelope envelope=soapPart.getEnvelope(); SOAPBody soapBody = envelope.getBody(); @SuppressWarnings("unchecked") Iterator<Node> itr=soapBody.getChildElements(); while (itr.hasNext()) { Node node=(Node)itr.next(); if (node.getNodeType()==Node.ELEMENT_NODE) { System.out.println("reading Node.ELEMENT_NODE"); Element ele=(Element)node; System.out.println("Body childs : "+ele.getLocalName()); switch (ele.getNodeName()) { case "VerifyEmailResponse": NodeList statusNodeList = ele.getChildNodes(); for(int i=0;i<statusNodeList.getLength();i++){ Element emailResult = (Element) statusNodeList.item(i); System.out.println("VerifyEmailResponse childs : "+emailResult.getLocalName()); switch (emailResult.getNodeName()) { case "VerifyEmailResult": NodeList emailResultList = emailResult.getChildNodes(); for(int j=0;j<emailResultList.getLength();j++){ Element emailResponse = (Element) emailResultList.item(j); System.out.println("VerifyEmailResult childs : "+emailResponse.getLocalName()); switch (emailResponse.getNodeName()) { case "ResponseText": System.out.println(emailResponse.getTextContent()); break; case "ResponseCode": System.out.println(emailResponse.getTextContent()); break; case "LastMailServer": System.out.println(emailResponse.getTextContent()); break; case "GoodEmail": System.out.println(emailResponse.getTextContent()); default: break; } } break; default: break; } } break; default: break; } } else if (node.getNodeType()==Node.TEXT_NODE) { System.out.println("reading Node.TEXT_NODE"); //do nothing here most likely, as the response nearly never has mixed content type //this is just for your reference } } // print SOAP Response System.out.println("Response SOAP Message:"); soapResponse.writeTo(System.out); soapConnection.close(); } private static SOAPMessage createSOAPRequest() throws Exception { MessageFactory messageFactory = MessageFactory.newInstance(); SOAPMessage soapMessage = messageFactory.createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); String serverURI = "http://ws.cdyne.com/"; // SOAP Envelope SOAPEnvelope envelope = soapPart.getEnvelope(); envelope.addNamespaceDeclaration("example", serverURI); /* Constructed SOAP Request Message: <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/"> <SOAP-ENV:Header/> <SOAP-ENV:Body> <example:VerifyEmail> <example:email>mutantninja@gmail.com</example:email> <example:LicenseKey>123</example:LicenseKey> </example:VerifyEmail> </SOAP-ENV:Body> </SOAP-ENV:Envelope> */ // SOAP Body SOAPBody soapBody = envelope.getBody(); SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example"); SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example"); soapBodyElem1.addTextNode("mutantninja@gmail.com"); SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example"); soapBodyElem2.addTextNode("123"); MimeHeaders headers = soapMessage.getMimeHeaders(); headers.addHeader("SOAPAction", serverURI + "VerifyEmail"); soapMessage.saveChanges(); /* Print the request message */ System.out.println("Request SOAP Message:"); soapMessage.writeTo(System.out); System.out.println(""); System.out.println("------"); return soapMessage; } 

}

对于WSDL的基本身份validation,接受的答案代码会产生错误。 尝试下面的代替

 Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username","password".toCharArray()); } }); 
 String send = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n" + " <soap:Body>\n" + " </soap:Body>\n" + "</soap:Envelope>"; private static String getResponse(String send) throws Exception { String url = "https://api.comscore.com/KeyMeasures.asmx"; //endpoint String result = ""; String username="user_name"; String password="pass_word"; String[] command = {"curl", "-u", username+":"+password ,"-X", "POST", "-H", "Content-Type: text/xml", "-d", send, url}; ProcessBuilder process = new ProcessBuilder(command); Process p; try { p = process.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); StringBuilder builder = new StringBuilder(); String line = null; while ( (line = reader.readLine()) != null) { builder.append(line); builder.append(System.getProperty("line.separator")); } result = builder.toString(); } catch (IOException e) { System.out.print("error"); e.printStackTrace(); } return result; }