Java client calling SOAP web service

Even Java Desktop applications can use web services, and in this article, we will take a look at how to make a call to a SOAP web service and receive a response.  For this simple example, we will make use of “The Naked Web Service” which was produced as an earlier article.

Let’s set the scene here.  This example is a simple Java application with no user interface, the output all goes to the console.  The only purpose of this program is to prove that we can consume the web service.

Now we know what we are about let us turn our attention to what our code needs to do.

We will start by opening a Connection to our web service using the URL that points to it.  What we actually want is an HTTP Connection but fortunately, we can cast the URL Connection to an HTTP Connection. 

Once we have the HTTP Connection, we can set various properties for the connection.  These are properties that specify or determine the connection characteristics and are used to negotiate the communication between the client and the service.

When we come to make the call to the web service, we will pass across XML that makes up the SOAP request.  Because this is a simple web service there is no SOAP header so most of the XML is contained within the body of the XML message.  We make a call to the sayHello method and pass two arguments, the name and the age.  That’s it.  Now to make it easy to produce this XML I used the software tool SOAPUI to generate the XML and copied and pasted it across.  Take a look at the article “The Naked Web Service” for more information about using SOAPUI with the web service.

The XML used is as follows:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:hel="http://helloage.app.web.softwarepulse/">
   <soapenv:Header/>
   <soapenv:Body>
      <hel:sayhello>
         <!--Optional:-->
         <arg0>?</arg0>
         <arg1>?</arg1>
      </hel:sayhello>
   </soapenv:Body>
</soapenv:Envelope>

With the XML all sorted let’s take a look at the connection properties we need to set before making the web service call.

For this example, we will set the length of the request sent to the service in bytes.  This is the number of bytes required to send the XML message as listed in the previous section.

The content type is set and the SOAP action which in this example there is no SOAP action.  The request method is POST and we will be sending information as well as receiving information from the server.

Once that is all set, we can get the output stream from the HTTP Connection, write our XML into the stream and then close the stream.

To get the response from the service we create a new Input Stream Reader from the response to the call to Get Input Stream method of the HTTP Connection.  We then read each line of the response and put that into a String.  Now the resultant response from the service is a series of XML.

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <ns2:sayhelloResponse xmlns:ns2="http://helloage.app.web.softwarepulse/">
         <return>Hello ?, I understand you are 0 years old.</return>
      </ns2:sayhelloResponse>
   </S:Body>
</S:Envelope>

The XML displayed here is indented but what we receive from the server has the XML all on a single line. 

In order to read specific items of data from the XML message, we can parse the XML (see method parseXML(String)).  To do this we create a Document Builder and input the XML source as an Input Source.  When we call the parse method of the Document Builder we get a Document in return.  This Document is a Document Object Model as used with HTML and XML.  It is made up of a series of Nodes representing a part of the XML message.

Once we have the Document, we get a list of the Nodes with the Tag Name that we are interested in.  For our Web Service, there is only a single node that contains data and only a single instance of this node.  So, we look for the Tag Name “ns2:sayhelloResponse” and this gives us a list of one item. 

We then access the Get Text Content method call for the Node and this provides us with the text response from the web service.

A simple message output to the console to display the result and there we have it our web service called from a simple Java application. The source code for this example is listed below

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


/**
 * @author jmcneil
 * (c) copyright Software Pulse 2020
 *
 */
public class TestHelloAge {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		TestHelloAge testHelloAge = new TestHelloAge();
		testHelloAge.geHelloAge("John", 33);
	}

	
	public void geHelloAge(String name, int age) {
		String wsURL = "http://localhost:8080/helloage/Hello2You";
	    URL url = null;
	    URLConnection connection = null;
	    HttpURLConnection httpConn = null;
	    String responseString = null;
	    String outputString="";
	    OutputStream out = null;
	    InputStreamReader isr = null;
	    BufferedReader in = null;
	    
		String xmlInput =
			    "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:hel=\"http://helloage.app.web.softwarepulse/\">" +
			    	    "<soapenv:Header/>" +
			    	    "<soapenv:Body>" +
			    	       "<hel:sayhello>" +
			    	          "<!--Optional:-->" +
			    	          "<arg0>" + name + "</arg0>" +
			    	          "<arg1>" + age + "</arg1>" +
			    	       "</hel:sayhello>" +
			    	    "</soapenv:Body>" +
			    	 "</soapenv:Envelope>";
	    
	    try
	    {
	        url = new URL(wsURL);
	        connection = url.openConnection();
	        httpConn = (HttpURLConnection) connection;

	        byte[] buffer = new byte[xmlInput.length()];
	        buffer = xmlInput.getBytes();

	        String SOAPAction = "";
	        // Set the appropriate HTTP parameters.
	         httpConn.setRequestProperty("Content-Length", String
	                 .valueOf(buffer.length));
	        httpConn.setRequestProperty("Content-Type",
	        		"text/xml; charset=utf-8");
	        
	        
	        httpConn.setRequestProperty("SOAPAction", SOAPAction);
	        httpConn.setRequestMethod("POST");
	        httpConn.setDoOutput(true);
	        httpConn.setDoInput(true);
	        out = httpConn.getOutputStream();
	        out.write(buffer);
	        out.close();
	        
	        // Read the response and write it to standard out.
	        isr = new InputStreamReader(httpConn.getInputStream());
	        in = new BufferedReader(isr);
	        
	        while ((responseString = in.readLine()) != null) 
	        {
	            outputString = outputString + responseString;
	        }
	        System.out.println(outputString);
	        System.out.println("");
	        
	        // Get the response from the web service call
	    	Document document = parseXmlFile(outputString);
	    	
	    	NodeList nodeLst = document.getElementsByTagName("ns2:sayhelloResponse");
	    	String webServiceResponse = nodeLst.item(0).getTextContent();
	    	System.out.println("The response from the web service call is : " + webServiceResponse);
	    	 
	    } 
	    catch (Exception e) 
	    {
	        e.printStackTrace();
	    }
	}
	
	private Document parseXmlFile(String in) {
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			 InputSource is = new InputSource(new StringReader(in));
			return db.parse(is);
		} catch (ParserConfigurationException e) {
			throw new RuntimeException(e);
		} catch (SAXException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

}

7 Replies to “Java client calling SOAP web service”

  1. Hello John ,
    Thanks so much for usefull information.
    I had worked on service client and got stucked, but your video and article helped me to dig deeper
    and hopefully to find a right way.
    I ve tested http basic autherization in soap and GZIPinput stream and SOAPMessage with your code
    Thanks a lot

    1. Hi Nick,
      Thanks for leaving a comment to let me know how you got on. It is great to see that you were able to use the example here to help you build your own personal application.
      Cheers John

  2. I am having this problem:
    “No binding operation info while invoking unknown method with params unknown” which is generated by line
    “isr = new InputStreamReader(httpConn.getInputStream());”

    Any idea?

    Thank you.

    1. I figured it out, it was my problem about SOAP request.

      Thank you very much for this super-educating work. You can’t know how you saved me for trying the understand the concept like for 2-3 days.

      1. Hi Furkan,
        Glad you were able to sort out your problem and it is good to hear that you found the blog useful. I wish you all the best in your future endeavours.
        Regards,
        John

  3. Man rasa harakat qildim, lekin hich nima tushunmadim. Buguncha yetadi, ertaga yana harakat qilaman. Hurmat va ehtirom ila Shakhzod!

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.