I\'m trying to find a simple (ha) SOAP example in JAVA with a working service, any I seem to be finding are not working.
I have tried this one from this example but it\'s just not working, it\'s asking me to put a forward slash in but it\'s in there and nothing happening.
So does anyone know any SOAP example links, I can download/request and mess with?
Thanks for your help.
To implement simple SOAP clients in Java, you can use the SAAJ framework (it is shipped with JSE 1.6 and above):
SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.
See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.
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;
}
}
Yes, if you can acquire any WSDL file, then you can use SoapUI to create mock service of that service complete with unit test requests. I created an example of this (using Maven) that you can try out.
Also, here is a giant list of free webservices someone posted.
The response of acdcjunior it was awesome, I just expand his explanation with the next code, where you can see how iterate over the XML elements.
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;
}
}
For Basic Authentication of WSDL the accepted answers code raises an error. Try the following instead
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;
}