Answers:
要用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[]) {
/*
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;
}
}
<faultcode>soap:Client</faultcode><faultstring>Server did not recognize the value of HTTP Header SOAPAction: .</faultstring>
MimeHeaders headers = soapMessage.getMimeHeaders(); headers.addHeader("SOAPAction", "http://ws.cdyne.com/VerifyEmail");
。我现在认为在没有它的情况下就可以工作很奇怪。:)
Map
的String
S代表更容易访问?
是的,如果您可以获取任何WSDL文件,则可以使用SoapUI创建该服务的模拟服务,并带有单元测试请求。我创建了一个示例(使用Maven),您可以尝试使用。
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的基本身份验证,接受的答案代码会引发错误。尝试以下方法
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;
}