Search code examples
javasoapjaxbsoap-clientsaaj

How to convert SoapResponse to pojos(Java classes) and Class Objects to Soap Request


I want to read Soap response - how can i convert soap response to pojos(Class objects) Also i want to send soap post request - how can i convert class objects to soap request.

I need both ways, can you please help here


Solution

  • If you want to marshal and unmarshal a SOAP message to POJOs, you can use xjc to generate JAXB bindings from the schema https://www.w3.org/2003/05/soap-envelope/.

    However SOAP is not usually unmarshaled using JAXB, but through a specialized framework: SOAP with Attachments API for Java. This framework can also unmarshal SOAPs with attachments: it's a multipart/related MIME document with an XML SOAP message and a series of attachments.

    To deserialize using SAAJ you use a MessageFactory and provide the MIME headers of the message and an input stream:

    final InputStream is = ...;
    final MimeHeaders mimeHeaders = ...;
    final SOAPMessage soap = MessageFactory.newInstance().createMessage(mimeHeaders, is);
    

    If you have SOAPMessage, you can access the parts you are interested in through getSOAPPart, getSOAPBody, getSOAPHeader which return you DOM interfaces, which you can transform to POJOs using JAXB.

    To serialize you just have to create a new SOAPMessage, fill it and call the writeTo method:

    final SOAPMessage soap = MessageFactory.newInstance().createMessage();
    ... // fill the message
    final OutputStream os = ...;
    soap.writeTo(os);