Introduction

This example will show you how to do a SOAP web service call from Java class. Normally you would use the web service library for invoking the SOAP service but in some cases this could be useful and quick. For example, you may have problems generating a client proxy with a web service library or if you only need some small specific parts of the response. It is just a SOAP call over HTTP from a plain piece of Java code without using any Java library. In fact you can invoke SOAP service from any language being web service platform independent.

Now in order to consume the service or SOAP web service call from Java class, we must have the service deployed somewhere. So please read Spring SOAP WebService Producers using Gradle before consuming this SOAP service. We will create here client which will consume the service in the given link. If you want to use library to consume the service then you can read Spring SOAP WebService Consumers using Gradle

Prerequisites

Knowledge of Java, SOAP, Java 1.8

Spring SOAP WebService Producers using Gradle

Example with Source Code

Finding the WSDL

In order to SOAP web service call from Java class first open the WSDl file at http://localhost:9999/ws/users.wsdl from tutorial Spring SOAP WebService Producers using Gradle.

In the WSDL file given in the above link, look for XSD, SOAP Operation and SOAP address location in the WSDL file. So you will find SOAP request name getUserDetailsRequest and SOAP response name getUserDetailsResponse. Also check for the input parameter(s) for request. Here we see only one parameter called name, which is of string type.

Request XML

We don’t need to build the response XML structure using Java code because we will get it from the server side but we need to build the request XML structure because we need to provide it as an input to the SOAP service.

Therefore if we build the request XML structure, it will look similar to below:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
	<getUserDetailsRequest xmlns="http://www.jeejava.com/UserService">
		<name>Liton Sarkar</name>
	</getUserDetailsRequest>
</soapenv:Body>
</soapenv:Envelope>

SOAP Address

Now find the SOAP address location, which is used as an endpoint URL for SOAP service and at this endpoint we will connect using Java’s HttpURLConnection API.

Here the endpoint URL is http://localhost:9999/ws

SOAP Operation

Next is to find the operation name, which will be used as a SOAP Action. Here it is getUserDetails.

Creating SOAP Client

Now we have identified all the required things and are ready to create the client class.

package com.jeejava.soap.client;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class SoapClient {
	public static void main(String[] args) throws IOException {
		// Code to make a webservice HTTP request
		String responseString = "";
		String outputString = "";
		String wsEndPoint = "http://localhost:9999/ws";
		URL url = new URL(wsEndPoint);
		URLConnection connection = url.openConnection();
		HttpURLConnection httpConn = (HttpURLConnection) connection;
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		String xmlInput = "<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header/><soapenv:Body><getUserDetailsRequest xmlns="http://www.jeejava.com/UserService"><name>Liton Sarkar</name></getUserDetailsRequest></soapenv:Body></soapenv:Envelope>";
		byte[] buffer = new byte[xmlInput.length()];
		buffer = xmlInput.getBytes();
		bout.write(buffer);
		byte[] b = bout.toByteArray();
		String SOAPAction = "getUserDetails";
		httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
		httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
		httpConn.setRequestProperty("SOAPAction", SOAPAction);
		httpConn.setRequestMethod("POST");
		httpConn.setDoOutput(true);
		httpConn.setDoInput(true);
		
		OutputStream out = httpConn.getOutputStream();
		// Write the content of the request to the outputstream of the HTTP
		// Connection.
		out.write(b);
		out.close();
		// Ready with sending the request.
		// Read the response.
		InputStreamReader isr = new InputStreamReader(httpConn.getInputStream(), Charset.forName("UTF-8"));
		BufferedReader in = new BufferedReader(isr);
		// Write the SOAP message response to a String.
		while ((responseString = in.readLine()) != null) {
						outputString = outputString + responseString;
		}
		// Write the SOAP message formatted to the console.
		String formattedSOAPResponse = formatXML(outputString);
		System.out.println(formattedSOAPResponse);
	}
	
	// format the XML in pretty String
	private static String formatXML(String unformattedXml) {
		try {
			Document document = parseXmlFile(unformattedXml);
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			transformerFactory.setAttribute("indent-number", 3);
			Transformer transformer = transformerFactory.newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			DOMSource source = new DOMSource(document);
			StreamResult xmlOutput = new StreamResult(new StringWriter());
			transformer.transform(source, xmlOutput);
			return xmlOutput.getWriter().toString();
		} catch (TransformerException e) {
			throw new RuntimeException(e);
		}
	}
	
	// parse XML
	private static 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 (IOException | ParserConfigurationException | SAXException e) {
			throw new RuntimeException(e);
		}
	}
}

Testing the Application

Now when you run the above Java class you will see the below output in the console.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header/>
   <SOAP-ENV:Body>
      <ns2:getUserDetailsResponse xmlns:ns2="http://www.jeejava.com/UserService">
         <ns2:users>
            <ns2:id>4</ns2:id>
            <ns2:name>Liton Sarkar</ns2:name>
            <ns2:email>liton.sarkar@email.com</ns2:email>
            <ns2:address>
               <ns2:street>Sukanta Nagar</ns2:street>
               <ns2:city>Kolkata</ns2:city>
               <ns2:state>WB</ns2:state>
               <ns2:zip>700098</ns2:zip>
               <ns2:country>India</ns2:country>
               <ns2:addressType>COMMUNICATION</ns2:addressType>
            </ns2:address>
         </ns2:users>
      </ns2:getUserDetailsResponse>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

That’s all. Thanks for reading.

Tags:

2 thoughts on “How to do a SOAP Web Service call from Java class

Leave a Reply

Your email address will not be published. Required fields are marked *