Building and sending a SOAP Envelope via Axis2 Client

The Apache Axis2┬álibrary is one of the world’s most renowned FOSS solutions for writing and deploying web services. This library ties in very closely with the Apache Axiom┬álibrary which is used to build the Object Model needed to send and receive SOAP messages for web services built using Axis2.

Today we’re going to take a look at how to build a SOAP envelope from a String value and how to set it to an Axis2 service client message context. There are a few things we need to do in order to accomplish this:

  1. Create a ServiceClient object.
  2. Create an Options object and set the endpoint URL for the service we’re going to call.
  3. Create a new MessageContext object.
  4. Create a SOAPEnvelope object from a given string using Axis2 TransportUtils.
  5. Set the SOAP envelope object to the MessageContext object.
  6. Use the ServiceClient object’s createClient method to generate an OperationClient object for this operation.
  7. Add the MessageContext object to the OperationClient object.
  8. Execute the OperationClient object.

Code:

final String MY_OM_STRING = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                        + "   <soapenv:Header/>\n"
                        + "   <soapenv:Body>\n"
                        + "     <my_xml_tag>My Value</my_xml_tag>\n"
                        + "   </soapenv:Body>\n"
                        + "  </soapenv:Envelope>";
//1. Create new ServiceClient object
ServiceClient serviceClient = new ServiceClient();

//2. Create an Options object and set the endpoint URL for the service we're going to call
Options serviceOptions = new Options();
serviceOptions.setTo(new EndpointReference(ENDPOINT_URL);
serviceClient.setOptions(serviceOptions);

//3. Create a new MessageContext object
MessageContext messageContext = new MessageContext();

//4. Create a SOAPEnvelope object from a given string
OMElement myOMElement = AXIOMUtil.stringToOM(MY_OM_STRING);
SOAPEnvelope soapEnvelope = TransportUtils.createSOAPEnvelope(myOMElement);

//5. Set the SOAP envelope object to the MessageContext object
messageContext.setEnvelope(soapEnvelope);

//6. Use the ServiceClient object's createClient method to generate an OperationClient
OperationClient opClient = serviceClient.createClient(ServiceClient.ANON_OUT_IN_OP);

//7. Add the MessageContext object to the OperationClient object
opClient.addMessageContext(messageContext);

//8. Execute the OperationClient object
opClient.execute(true);

And that’s how its done.