如何打印SOAPMessage

6

SOAPMessage有一个writeTo()方法,可将其内容输出到流中。但我该如何将SOAPMessage的内容写入StringBuffer呢?

需要修改代码行“message.writeTo(System.out);”。

public boolean handleMessage(SOAPMessageContext smc) {
     StringBuffer sbuf = new StringBuffer();
     sbuf.append("\n------------------------------------\n");
     sbuf.append("In SOAPHandler " + HandlerName + ":handleMessage()\n");

     Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

     if (outboundProperty.booleanValue()) {
        sbuf.append("\ndirection = outbound ");
     }
     else {
        sbuf.append("\ndirection = inbound ");
     }

     SOAPMessage message = smc.getMessage();      
     try {
        sbuf.append("\n");
        sbuf.append(message.toString());         
        //message.writeTo(System.out);         
        sbuf.append("\nMessage Desc:");         
        sbuf.append("\n");
     }
     catch (Exception e) {
        sbuf.append("Exception in SOAP Handler: " + e);
     }

     sbuf.append("Exiting SOAPHandler " + HandlerName + ":handleMessage()\n");
     sbuf.append("------------------------------------\n");
     logger.debug(sbuf.toString());
     return true;
  }
2个回答

9

好的,我已经解决了这个问题。修改后的代码块如下。

  public boolean handleMessage(SOAPMessageContext smc) {
     StringBuffer sbuf = new StringBuffer();
     sbuf.append("\n------------------------------------\n");
     sbuf.append("In SOAPHandler " + HandlerName + ":handleMessage()\n");

     Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

     if (outboundProperty.booleanValue()) {
        sbuf.append("\ndirection = outbound ");
     }
     else {
        sbuf.append("\ndirection = inbound ");
     }

     SOAPMessage message = smc.getMessage();      
     try {
        sbuf.append("\n");
        sbuf.append(message.toString()); 
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        message.writeTo(baos);                     
        sbuf.append("\nMessage Desc:"+baos.toString());         
        sbuf.append("\n");
     }
     catch (Exception e) {
        sbuf.append("Exception in SOAP Handler: " + e);
     }

     sbuf.append("Exiting SOAPHandler " + HandlerName + ":handleMessage()\n");
     sbuf.append("------------------------------------\n");
     logger.debug(sbuf.toString());
     return true;
  }

1
如果您只是为了调试目的而需要记录SOAP消息,那么最好的方法是在JAX-WS实现中打开SOAP消息日志记录。在这种情况下,您不需要编写任何代码。

您可以使用处理程序链 - 并有多个处理程序来装饰输入/输出消息。打印中间内容具有其用途。 - razvanone

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接