SOAP Client in java

If you are looking for java client for RESTful web service then you should visit this article:

Simple REST client in java

This article will teach you how to create a SOAP client in java. That is creating a client in java which requests soap server (no need to be in java) and get response from it. First create request message as follows:

SOAPMessage message = MessageFactory.newInstance().createMessage();
SOAPHeader header = message.getSOAPHeader();
header.detachNode();

If you have namespace required in SOAP request then add those namespaces to envelope element as follows:

SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
envelope.setAttribute("namspace","namespaceUrl");

You can add as many attribute as you want. Now time to create request message body.
Following body is made assuming that SOAP server where this client will connect will have a public service method called getResponse(name) available.

SOAPBody body = message.getSOAPBody();
QName bodyName = new QName("getResponse");
SOAPBodyElement bodyElement = body.addBodyElement(bodyName);
SOAPElement symbol = bodyElement.addChildElement("name");
symbol.addTextNode(“Harry joy”);

Now that request message is ready it’s time to connect to soap server and send request. Following code will do this:

SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection();
SOAPMessage response = connection.call(message, endpoint);
connection.close();

In above code endpoint is the SOAP server URL without “?wsdl”. To parse response you can do as follows:

SOAPBody responseBody = response.getSOAPBody();
SOAPBodyElement responseElement = (SOAPBodyElement)responseBody.getChildElements().next();
SOAPElement returnElement = (SOAPElement)responseElement.getChildElements().next();
if(responseBody.getFault() != null) { //-- If response has any fault.
 	System.out.println(returnElement.getValue()+" "+responseBody.getFault().getFaultString());
}  else  {
   	System.out.println(returnElement.getValue());
}

Here request/response messages are totally dependent on SOAP server, how you have configured it.


Bonus: How to print request/response xml?

String getXmlFromSOAPMessage(SOAPMessage msg) throws SOAPException, IOException {
	ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
	msg.writeTo(byteArrayOS);
	return new String(byteArrayOS.toByteArray());
}

Use:

System.out.println(getXmlFromSOAPMessage(message));
System.out.println(getXmlFromSOAPMessage(response));

Full source code:

public class SOAPClient {

	private static final String endpoint = "http://localhost/SOAPService/MySoapService";

	public static void main(String[] args) throws SOAPException {
		SOAPMessage message = MessageFactory.newInstance().createMessage();
		SOAPHeader header = message.getSOAPHeader();
		header.detachNode();

		SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
		envelope.setAttribute("namespace","namespaceUrl");

		SOAPBody body = message.getSOAPBody();
		QName bodyName = new QName("getResponse");
		SOAPBodyElement bodyElement = body.addBodyElement(bodyName);
		SOAPElement symbol = bodyElement.addChildElement("name");
		symbol.addTextNode("Harry Joy");

		SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection();
		SOAPMessage response = connection.call(message, endpoint);
		connection.close();

		SOAPBody responseBody = response.getSOAPBody();
		SOAPBodyElement responseElement = (SOAPBodyElement)responseBody.getChildElements().next();
		SOAPElement returnElement = (SOAPElement)responseElement.getChildElements().next();
		if(responseBody.getFault()!=null){
			System.out.println(returnElement.getValue()+" "+responseBody.getFault().getFaultString());
		} else {
			System.out.println(returnElement.getValue());
		}

		try {
			System.out.println(getXmlFromSOAPMessage(message));
			System.out.println(getXmlFromSOAPMessage(response));
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private static String getXmlFromSOAPMessage(SOAPMessage msg) throws SOAPException, IOException {
		ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
		msg.writeTo(byteArrayOS);
		return new String(byteArrayOS.toByteArray());
	}

}
About these ads

About harryjoy
A passionate self-taught software developer. Currently working as Software Engineer in an IT company located in INDIA.

10 Responses to SOAP Client in java

  1. Pingback: JavaPins

  2. Hi… is there a way to use it with NTLM? Thanks in advance

    • harryjoy says:

      Hi Marcelo,

      Sorry but I have never worked with NTLM, so can not make a statement here. But after a little search on internet I found that this is possible, you should try SOAP-UI.

      Thanks & Regards.

  3. sahatanumi says:

    jdk1.6 and php soap client : http://biclim.com/WSClients.action

  4. Eduardo says:

    I have a problem when connect with this code because the webservice return the message with conten-type application/xml and trigger a Exception “Invalid conten-type: application/xml. Is this an error mesage instead of a SOAP Response? ” You know how to resolve this??

    • harryjoy says:

      Hi Eduardo,

      I tried this code with a web service generating XML response and worked perfect. You should check the request XML you are sending is valid at server side. It can be possible that either you are not sending any content or too long contents or content you are sending in request is not in valid format for the server. If you want me to debug the issue then you have to send web service address and other associated details run this program on my personal email id, if its feasible for you. You can find my email id on about page. I’ll still try to see if I can reproduce this error and let you know the update. Also telling line on which you are getting this exception will be a good help to debug it.

  5. puccio says:

    SEI UN GRANDEEEEEEEEE!!!!!!!!!

  6. hi I am getting [ Unable to handle request without a valid action parameter. Please supply a valid soap action. ] error when I use your code with endpoint = “http://www.webservicex.net/country.asmx?WSDL” , QName bodyName = new QName(“GetCurrencyByCountry”); , SOAPElement symbol = bodyElement.addChildElement(“CountryName”);
    symbol.addTextNode(“Singapore”); I want make a sample call to http://www.webservicex.net/country.asmx?op=GetCurrencyByCountry . Can you help me out?

  7. Adam says:

    Being a novice with Java, and required to call a Web Service with very limited time to implement a solution, your post has proven to be BY FAR the most helpful bit of information I have come across in the last 20 hours of research. Thank you!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 39 other followers

%d bloggers like this: