Tuesday, October 7, 2008

Axis2 - Adding custom SOAP Headers to a request using ServiceClient

The Axis2 ServiceClient API provides three main ways of adding SOAP Headers to a request. Lets take a look at how this could be done,

  • Add a simple header which contains a String to the request


serviceClient.addStringHeader(new QName("http://wso2.org", "ThirdHeader"), "This is a sample Header");

This is the simplest method of adding a header. But this method restricts you to simple String headers.

  • Creating a header as a OMElement and adding it to the request


OMElement firstHeader = AXIOMUtil.stringToOM(
"This is a sample Header");
serviceClient.addHeader(firstHeader);

Users are expected to create the complete header themselves using Axiom's OMElement APIs.

  • Creating a header as a SOAPHeaderBlock and adding it to the request


OMNamespace omNamespace =
OMAbstractFactory.getOMFactory().createOMNamespace("http://wso2.com", "ws");
SOAPHeaderBlock secondHeader = OMAbstractFactory.getSOAP12Factory().createSOAPHeaderBlock("SecondHeader", omNamespace);
secondHeader.addChild(AXIOMUtil.stringToOM("This is a sample Header"));
//secondHeader.setMustUnderstand(true);
serviceClient.addHeader(secondHeader);

Users are expected to create the header using Axiom's SOAP APIs. Users could use the API to set various options on the header such as the MustUnderstand Attribute.

3 comments:

Milinda Lakmal Pathirage said...

Use Axis2/C service client to add custom SOAP Headers.

Raksh said...

Keith,
I've been trying to find ways to be able to read SOAP header tag from my input xml string (XMLStreamReader). There are dynamic values in the header tag that need to be passed for authentication purposes.
Currently, my code complains of "Unexpected subelement XXX" if I add any sOAP tags (envelope, header, body) in the input xml string.
Could you share your thoughts on how you think this issue could be fixed.
Thanks!!
wsNewbie

kumar said...
This comment has been removed by the author.