Java A Simple SAAJ client

SAAJ webservice client example.


SOAP with Attachments API for Java provides the standard way to send XML documents over the network for the java platform.
We can send direct SOAP messages instead using any API's like jax-ws , Axis etc.

We will send soap request to a public webservice and get the response out of the service.

For experiment purpose we use the weather service webservice available at the endpoint

Below is the SOAP message to send to this webservice.

SOAP message

    <SOAP-ENV:Header />
        <ns1:GetCityForecastByZIP xmlns:ns1=''>

 * Simple SAAJ client for a publically available Webservice.
 * The service is WEATHER service. 
package com.service;


import javax.xml.soap.*;
import javax.xml.transform.*;

 * @author bala
public class SaajClient {
 // SOAP message as string, you can read it from file, n/w source etc

 private static String soapMessage = " " +
   "   " +
   "29602  ";
 private static final String endPoint = "";
 public static void main(String[] args) throws Exception {
  setProxy(); // set proxy if you are behind the firewall 

  SOAPMessage message = sendMessage();

 private static SOAPMessage sendMessage() throws Exception {

  SOAPConnectionFactory sFactory = SOAPConnectionFactory.newInstance();
  SOAPConnection sConnection = sFactory.createConnection();
  MessageFactory messageFactory = MessageFactory.newInstance();
  SOAPMessage message = messageFactory.createMessage();

  SOAPPart soapPart = message.getSOAPPart();
  SOAPEnvelope envelope = soapPart.getEnvelope();

  // To read the SOAP message from file, here we use the string variable, so this is commented out.
  /*StreamSource preppedMsgSrc = new StreamSource(new FileInputStream("file_location"));
  soapPart.setContent(new StreamSource(new StringReader(soapMessage)));
  System.out.println("Content set!");


  String destination = endPoint;
  URL url = new URL(destination);
  SOAPMessage reply  =, url);
  System.out.println("Request sent!");

  System.out.println("connection closed!");
  return reply;

 private static void readResponse(SOAPMessage message) throws Exception {

  System.out.println("message here ;" + message);
  TransformerFactory transformerFactory = TransformerFactory.newInstance();
  Transformer transformer = transformerFactory.newTransformer();
  Source sourceContent = message.getSOAPPart().getContent();
  StreamResult result = new StreamResult(System.out);

  transformer.transform(sourceContent, result);


Running above code will give following output in the console. This output is the webservice response.
Response from the webservice is looks like below.

<soap:Envelope xmlns:soap=""
    <ResponseText>City Found</ResponseText>  


Popular posts from this blog

Log4j multiple WAR files in single EAR configuration

Java NIO2 - Watching a directory for changes. FileWatcherService.

Ubuntu / kubuntu - Laptop key board cursor jumping issue