Getting Raw XML From SOAPMessage in Java

前端 未结 9 1875
醉梦人生
醉梦人生 2020-12-02 06:41

I\'ve set up a SOAP WebServiceProvider in JAX-WS, but I\'m having trouble figuring out how to get the raw XML from a SOAPMessage (or any Node) object. Here\'s a sample of t

相关标签:
9条回答
  • 2020-12-02 07:03

    You could try in this way.

    SOAPMessage msg = messageContext.getMessage();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    msg.writeTo(out);
    String strMsg = new String(out.toByteArray());
    
    0 讨论(0)
  • 2020-12-02 07:04

    this works

     final StringWriter sw = new StringWriter();
    
    try {
        TransformerFactory.newInstance().newTransformer().transform(
            new DOMSource(soapResponse.getSOAPPart()),
            new StreamResult(sw));
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
    System.out.println(sw.toString());
    return sw.toString();
    
    0 讨论(0)
  • 2020-12-02 07:06

    It turns out that one can get the raw XML by using Provider<Source>, in this way:

    import java.io.ByteArrayOutputStream;
    import javax.xml.transform.Source;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.ws.Provider;
    import javax.xml.ws.Service;
    import javax.xml.ws.ServiceMode;
    import javax.xml.ws.WebServiceProvider;
    
    @ServiceMode(value=Service.Mode.PAYLOAD)
    @WebServiceProvider()
    public class SoapProvider implements Provider<Source>
    {
        public Source invoke(Source msg)
        {
            StreamResult sr = new StreamResult();
    
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            sr.setOutputStream(out);
    
            try {
                Transformer trans = TransformerFactory.newInstance().newTransformer();
                trans.transform(msg, sr);
    
                // Use out to your heart's desire.
            }
            catch (TransformerException e) {
                e.printStackTrace();
            }    
    
            return msg;
        }
    }
    

    I've ended up not needing this solution, so I haven't actually tried this code myself - it might need some tweaking to get right. But I know this is the right path to go down to get the raw XML from a web service.

    (I'm not sure how to make this work if you absolutely must have a SOAPMessage object, but then again, if you're going to be handling the raw XML anyways, why would you use a higher-level object?)

    0 讨论(0)
提交回复
热议问题