Monday, January 3, 2011

Develop Web Service With Axis2 #5 - Custom Soap Header on Stub side

Prev >>> Develop Web Service With Axis2 #4 - Axis2 Style Interceptor 

1) if only add a simple string to header 


--- stub code

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

-- soap message

<?xml version='1.0' encoding='utf-8'?>
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
  <soapenv:Header>
     <myHeader:header xmlns:myHeader="http://mycompany.org">
        This is a custom soap header
     </myHeader:header>
   </soapenv:Header>
   <soapenv:Body>
      <ns2:getUserInfo xmlns:ns2="http://axis.test.com/ws" />
    </soapenv:Body>
</soapenv:Envelope>

2) to use OMElement object to encapsulate soap header

--- stub code

OMElement header1 = AXIOMUtil.stringToOM("<header1><systemId>system-011</systemId></header1>");
OMElement header2 = AXIOMUtil.stringToOM("<header2><requestTime>"+new java.util.Date()+"</requestTime></header2>");
 _stub._getServiceClient().addHeader(header1);
 _stub._getServiceClient().addHeader(header2);

--- soap message

<?xml version='1.0' encoding='utf-8'?>
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
<soapenv:Header>
   <header1>
       <systemId>system-011</systemId>
   </header1>
   <header2>
       <requestTime>Mon Jan 03 14:29:00 CST 2011</requestTime>
   </header2>
</soapenv:Header>
<soapenv:Body>
<ns2:getUserInfo xmlns:ns2="http://axis.test.com/ws" />
</soapenv:Body>
</soapenv:Envelope>

3. SOAPHeaderBlock

--- stub code

OMNamespace omNamespace = OMAbstractFactory.getOMFactory()
                    .createOMNamespace("http://myCompany.com", "headerNs");
SOAPHeaderBlock header1 = OMAbstractFactory.getSOAP12Factory()
                    .createSOAPHeaderBlock("header1", omNamespace);
header1.addChild(AXIOMUtil.stringToOM("<header123>header content</header123>"));
_stub._getServiceClient().addHeader(header1);

---- soap message

<?xml version='1.0' encoding='utf-8'?>
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
<soapenv:Header>
    <headerNs:header1 xmlns:headerNs="http://myCompany.com">
         <header123>header content</header123>
    </headerNs:header1>
</soapenv:Header>
<soapenv:Body>
<ns2:getUserInfo xmlns:ns2="http://axis.test.com/ws" />
</soapenv:Body>
</soapenv:Envelope>

Reference
http://wso2.org/library/3156

No comments:

Post a Comment