How to Add Custom SOAP Headers to a Web Service Request in Axis2?

The Apache Axis2 client API provides you a convenient mechanism to talk to a Web service. You can simply pass the payload you need to send and Axis2 will take care of the rest. But what if you are interested in more than what is being sent in the body of the SOAP message? What if you want to add custom headers to the request?

Date: Sat, 2nd Dec, 2006
Level:
Reads: 20420 Comments: 0 | Login or register to post comments
Eran Chinthaka
Software Engineer
WSO2 Inc.
chinthaka's picture

Let's see how you can add your own headers to the request using Axis2 client API. Let's use the following header as an example.

<myNs:MyHeader xmlns:mvNS="http://www.CustomHeaders.com">This is some vital 
information<myNS:MyHeader>

Adding Custom Headers Using Client API

Step 1: First you need to get hold of the ServiceClient API. If you are not using generated stubs, then you should use ServiceClient to call the method. But if you are using generated stubs, using Axis2 WSDL2Code mechansim, call _getServiceClient() you can get hold of the ServiceClient.

ServiceClient serviceClient = XXXStub._getServiceClient(); 

Step 2: There are couple of methods in ServiceClient API that you can use to add SOAP headers. The easiest one is to use addStringHeader(QName headerName, String headerText) method.

serviceClient.addStringHeader(new QName("http://www.CustomHeaders.com", 
"MyHeader", "myNs"), "This is some vital information");

If you want more control than the above, for instance if you want to add a whole XML fragment inside the SOAP header, then you might want to consider using either addHeader(OMElement header) or addHeader(SOAPHeaderBlock header)

OMFactory omFactory = OMAbstractFactory.getOMFactory();
OMElement omElement = omFactory.createOMElement
(new QName("http://www.CustomHeaders.com", "MyHeader", "myNs"), null);
omElement.setText("This is some vital information");

// add whatever you want to omElement here

client.addHeader(omElement);

Applies To:

Apache Axis2/Java v1.1

For More Information:

AXIOM - Fast and Lightweight Object Model for XML

library project main code
Learn Cloud
Learn
Cloud

The WSO2 Application Server is a reliable application server that can host your enterprise web applications. The WSO2 Application Server as a Service is offered in StratosLive, the WSO2 Platform as a Service. This article explains how a simple web application can be developed and deployed from Carbon Studio to the WSO2 Application Server...

Latest Webinar
Different groups within an organization need to monitor different Key Performance Indicators (KPIs) - An operations team will be interested in the response times of business services and loads of each service,..
Thursday, February 9th 2012, 09.00 AM (PST)

Thursday, February 9th 2012, 10.00 AM (GMT)