Friday, April 8, 2011

Creating a soap message in java using SAAJ

Installation issues
Setting up the Java Web Services Developer Pack 1.2 is easy -- as long as you send your messages through the included Tomcat Web server. To send messages through a standalone application, as I do here, you need to take the following steps:
  1. Download the JWSDP 1.2 from
  2. Follow the instructions and install.
Example of soap message to be created : 

    <SOAP-ENV:Header />
        <ns1:Price xmlns:ns1="urn:xmethods-BNPriceCheck" >340

Now it has 2 parts - name and price , which it wants to submit to the service.
Notice the structure of the message. The Envelope contains the Header and Body elements, and all three are part of the namespace. The application sends the message using a SOAPConnection.

Creating the message object
//Next, create the actual message
         MessageFactory messageFactory = MessageFactory.newInstance();
         SOAPMessage message = messageFactory.createMessage();
         //Create objects for the message parts            
         SOAPPart soapPart =     message.getSOAPPart();
         SOAPEnvelope envelope = soapPart.getEnvelope();
         SOAPBody body =         envelope.getBody();

First, you create the message itself by using the MessageFactory. This message already contains empty versions of the basic parts, such as the envelope and header. The SOAPPart contains the envelope, and the envelope contains the body. Create references to the needed objects, such as the SOAPBody.

Populating the body:
The body of the SOAP message is just like any other XML element in that you can add a child element, such as Price.
//Populate the body
        //Create the main element and namespace
        SOAPElement bodyElement = 
                  body.addChildElement(envelope.createName("Price" , 
      SOAPElement authorElement = body.addChildElement(envelope.createName("AuthorName");
        //Save the message

        //Check the input
So this is how our message is prepared and now we can send it as request.

No comments:

Post a Comment