Monday, April 27, 2015

Pretty printing SOAP messages. (60 of 285 technotes for 2015)

Handy Java code to print SOAPMessages

References: - http://bit.ly/1dkVWoW


public static String getSOAPMessageAsString(SOAPMessage soapMessage) {
     try {

        TransformerFactory tff = TransformerFactory.newInstance();
        Transformer tf = tff.newTransformer();

        // Set formatting
       
        tf.setOutputProperty(OutputKeys.INDENT, "yes");
        tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
              "2");
       

        Source sc = soapMessage.getSOAPPart().getContent();

        ByteArrayOutputStream streamOut = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(streamOut);
        tf.transform(sc, result);

        String strMessage = streamOut.toString();
        return strMessage;
     } catch (Exception e) {
        System.out.println("Exception in getSOAPMessageAsString "
              + e.getMessage());
        return null;
     }

  }

No comments: