Thursday, May 31, 2012

Create Simple SOAP Request Message Using SAAJ API


The SOAP with Attachments API for Java (SAAJ) enables developers to produce and consume messages conforming to the SOAP 1.1 and SOAP 1.2 specification and also and SOAP with Attachments note.

Hear is a simple example code to produce SOAP request message to get user detail using SAAJ API.

public void createSOAPRequestMessage () {

    MessageFactory messageFactory = MessageFactory

               .newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);

  SOAPMessage soapMessage = messageFactory.createMessage();

        SOAPPart soapPart = soapMessage.getSOAPPart();

        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

        SOAPBody soapBody = soapEnvelope.getBody();

        soapEnvelope.addNamespaceDeclaration("xsi","http://www.w3.org/2001/XMLSchema-instance");

        soapEnvelope.addNamespaceDeclaration("xsd","http://www.w3.org/2001/XMLSchema");

        soapMessage.getSOAPHeader().detachNode();

        QName qNameRootTag = new QName("http://www.example.com/","GetUserDetail");

        SOAPBodyElement soapRootBodyElement = soapBody.addBodyElement(qNameRootTag);

        QName username = new QName("username");

        SOAPElement inputTagOne = soapRootBodyElement.addChildElement(username);

        inputTagOne.addTextNode("Mr Goni");

        QName userid = new QName("userid");

        SOAPElement inputTagTwo = soapRootBodyElement.addChildElement(userid);

        inputTagTwo.addTextNode("W2012X");

        soapMessage.saveChanges(); 

  soapMessage.writeTo(System.out);

        System.out.println();

}

This code will produce output like :





 

 Mr Goni
 W2012X

 






So , grub the code test and use or modify as your need .

No comments:

Post a Comment