Pages

Thursday, March 6, 2014

Build and Send a SOAP message to a webservice

Below is an example on how to build and send a SOAP message to a web service.

MyWebservice accepts Name (String) as input and returns a hello message (String) as output.

Here is a piece of code which builds and sends the SOAP message to a MyWebservice



package demo.ws;

import javax.xml.soap.*;

import java.util.*;
import java.net.URL;

public class MySOAPRequestBuilder {
 public static void main(String[] args) {
  try {
   SOAPConnectionFactory scFactory = SOAPConnectionFactory
     .newInstance();
   SOAPConnection con = scFactory.createConnection();

   MessageFactory factory = MessageFactory.newInstance();
   SOAPMessage message = factory.createMessage();

   SOAPPart soapPart = message.getSOAPPart();
   
   //Getting SOAP Envelope
   SOAPEnvelope envelope = soapPart.getEnvelope();
   
   //Getting SOAP Header
   SOAPHeader header = envelope.getHeader();
   
   //Getting SOAP Body
   SOAPBody body = envelope.getBody();
   header.detachNode();

   Name bodyName = envelope.createName("sayHello", "m",
     "http://ws.demo");
   SOAPBodyElement gltp = body.addBodyElement(bodyName);

   Name name = envelope.createName("name");
   SOAPElement symbol = gltp.addChildElement(name);
   symbol.addTextNode("Foo");

   URL endpoint = new URL(
     "http://localhost:8080/MyWS/services/MyWebService/sayHello");
     
   //Sending SOAP message to Endpoint and collecting response object
   SOAPMessage response = con.call(message, endpoint);

   con.close();

   //Reading response object
   SOAPPart sp = response.getSOAPPart();
   SOAPEnvelope se = sp.getEnvelope();
   SOAPBody sb = se.getBody();

   //Iterating through SOAP Body Elements
   Iterator it = sb.getChildElements();
   SOAPBodyElement sbe = (SOAPBodyElement) it.next();
   
   //Iterating through SOAP elements
   Iterator it1 = sbe.getChildElements();
   SOAPElement se1 = (SOAPElement) it1.next(); 
   
   //Printing response to console
   System.out.print("Response is ");
   System.out.print(se1.getValue());
   

  } catch (Exception ex) {
   ex.printStackTrace();
  }
 }
}



Output of the code: 

Response is Hello Foo !!!!



Example SOAP Request:

 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://ws.demo" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <soapenv:Body>
 <q0:sayHello>
  <q0:name>Foo</q0:name>
  </q0:sayHello>
  </soapenv:Body>
  </soapenv:Envelope>


Example SOAP Response:

 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
 <soapenv:Body>
 <ns:sayHelloResponse xmlns:ns="http://ws.demo">
  <ns:return>Hello Foo !!!!</ns:return>
  </ns:sayHelloResponse>
  </soapenv:Body>
  </soapenv:Envelope>