Monday, 4 April 2016

How to add SOAP header elements in Axis 1x client stubs ?


Sometimes a web service will also require you to include SOAP Header information, usually for login purposes.

In the case of explicit headers (that are defined in the WSDL), the SOAP Header information is supposed to be writable directly from the Axis client code.

There are two kinds of header elements you may have to generate.
The first are elements that are simply child nodes of the <Header> element, like so : 
<SOAP-ENV:Envelope......>
  <SOAP-ENV:Header>
      <ns1:UserName xmlns:ns1="urn:thisNamespace">
        John Doe
      </ns1:UserName>
  </SOAP-ENV:Header>
  <SOAP-ENV:Body>
      ..........
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

This type of envelope can be created with client code similar to this :
StockInfoServiceLocator locator = new StockInfoServiceLocator();
StockInfoService service = locator.getStockService();
// Add a <UserName> node to the SOAP Header
((Stub) service).setHeader("urn:thisNamespace", "UserName", "John Doe");
service.GetStockInfo("FOO");

You can also end up with header elements that are nested, such that there are nodes with subnodes within the <Header> element, like
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" 
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  <SOAP-ENV:Header>
    <ns1:AuthenticationInfo xmlns:ns1="urn:thisNamespace">
       <ns1:UserName>John Doe</ns1:UserName>
    </ns1:AuthenticationInfo>
  </SOAP-ENV:Header>
  <SOAP-ENV:Body>
      - - - - - - - - -
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

In this case, the <UserName> node is within an <AuthenticationInfo> node within the SOAP Header.

This type of envelope can be created with client code similar to this :
StockInfoServiceLocator locator = new StockInfoServiceLocator();
StockInfoService service = locator.getStockService();

// Add an <AuthenticationInfo> node with a <UserName> subnode to the SOAP Header
SOAPHeaderElement header = 
   new SOAPHeaderElement("urn:thisNamespace", "AuthenticationInfo");
SOAPElement node = header.addChildElement("UserName");
node.addTextNode("John Doe");
((Stub) service).setHeader(header);

// Call service
service.GetStockInfo("FOO");

No comments:

Post a Comment

Note: only a member of this blog may post a comment.