Sunday, October 12, 2008

How to add a custom SOAP header to the request using AXIOM

Suppose you want to add the following SOAP header block to your web service request message.
<myNS:header xmlns:myNS="http://ws.org">
This is a custom soap header
</myNS:header >

There are different approaches to add user defined headers to the request soap messages. Lets see how it could be done using AXIOM in simpler way.
In this example we are going to invoke Axi2 default version service with adding a custom soap header in to the request.

Pre-requisites
Download and install Apache Axis2
Install Apache Tcpmon

Step 1

Start Axis2 server by running AXIS2_HOME/bin/axis2server.bat{sh}
Go to http://localhost:8080. You will see that the default version service is deployed there.

Step 2

Now, we need to generate client stubs. Go to AXIS2_HOME/bin and run wsdl2java.bat{sh} with the following parameters.
WSDL2Java -uri http://localhost:8080/axis2/services/Version?wsdl -o out -uw

The client stubs will be generated in a directory called "out".

Now, write a client importing the generated stub classes as follows(You can easily create a project in Eclipse using the generated Build.xml)

import java.rmi.RemoteException;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import sample.axisversion.ExceptionException0;
import sample.axisversion.VersionStub;


public class CustomSoapHeaderClient {

public static void main(String[] args) throws AxisFault{

String url = "http://localhost:8090/axis2/services/Version";
VersionStub stub = new VersionStub(url);

OMFactory omFactory =OMAbstractFactory.getOMFactory();
OMNamespace omNamespace = omFactory.createOMNamespace("http://ws.org", "myNS");
OMElement header = omFactory.createOMElement("header", omNamespace);
header.setText("This is a custom soap header");
stub._getServiceClient().addHeader(header);

try {
System.out.println(stub.getVersion());
} catch (RemoteException e) {
e.printStackTrace();
} catch (ExceptionException0 e) {
e.printStackTrace();
}
}


}

Note the highlighted code which creates the custom soap header.

Step 3

We can visualize the soap request using Tcpmon. Therefore open tcpmon and configure listen port in 8090 and target port 8080.
Compile and run the above client. You will see the following message in request pane of Tcpmon.

<?xml version='1.0' encoding='UTF-8'?>
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
<soapenv:Header>
<myNS:header xmlns:myNS="http://ws.org">This is a custom soap header</myNS:header>


No comments:

Post a Comment