使用JAX-WS跟踪XML请求/响应

问题描述 投票:149回答:16

是否有一种简单的方法(也就是说:不使用代理)来访问使用JAX-WS参考实现(JDK 1.5及更高版本中包含的那个)发布的Web服务的原始请求/响应XML?能够通过代码实现这一点是我需要做的。只需通过巧妙的日志记录配置将其记录到文件中就可以了。

我知道其他更复杂和完整的框架可能会这样做,但我希望尽可能简单,并且axis,cxf等都会增加我想要避免的大量开销。

谢谢!

java web-services jax-ws
16个回答
257
投票

以下选项可以将所有通信记录到控制台(从技术上讲,您只需要其中一个,但这取决于您使用的库,因此将所有四个设置为更安全的选项)。您可以在示例中的代码中设置它,或者使用-D作为命令行参数,或者像Upendra所写的那样在环境变量中设置它。

System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump", "true");
System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dumpTreshold", "999999");

有关详细信息,请参阅问题Tracing XML request/responses with JAX-WS when error occurs


1
投票

您可以尝试将ServletFilter放在Web服务的前面,并检查从服务转发/返回的请求和响应。

虽然你特别没有要求代理,但有时我发现tcptrace足以看到连接上发生了什么。这是一个简单的工具,没有安装,它确实显示数据流,也可以写入文件。


1
投票

在运行时,您可以简单地执行

com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump = true

因为dump是类中定义的public var,如下所示

public static boolean dump;

1
投票

我是否理解您想要更改/访问原始XML消息?

如果是这样,你(或者因为这是五岁,下一个人)可能想要查看作为JAXWS一部分的Provider接口。客户端对应方使用“Dispatch”类完成。无论如何,您不必添加处理程序或拦截器。当然,你仍然可以。缺点是这样,你完全负责构建SOAPMessage,但它很容易,如果这就是你想要的(就像我做的那样),这是完美的。

这是服务器端的一个例子(有点笨拙,它只是用于实验) -

@WebServiceProvider(portName="Provider1Port",serviceName="Provider1",targetNamespace = "http://localhost:8123/SoapContext/SoapPort1")
@ServiceMode(value=Service.Mode.MESSAGE)
public class Provider1 implements Provider<SOAPMessage>
{
  public Provider1()
  {
  }

  public SOAPMessage invoke(SOAPMessage request)
  { try{


        File log= new File("/home/aneeshb/practiceinapachecxf/log.txt");//creates file object
        FileWriter fw=new FileWriter(log);//creates filewriter and actually creates file on disk

            fw.write("Provider has been invoked");
            fw.write("This is the request"+request.getSOAPBody().getTextContent());

      MessageFactory mf = MessageFactory.newInstance();
      SOAPFactory sf = SOAPFactory.newInstance();

      SOAPMessage response = mf.createMessage();
      SOAPBody respBody = response.getSOAPBody();
      Name bodyName = sf.createName("Provider1Insertedmainbody");
      respBody.addBodyElement(bodyName);
      SOAPElement respContent = respBody.addChildElement("provider1");
      respContent.setValue("123.00");
      response.saveChanges();
      fw.write("This is the response"+response.getSOAPBody().getTextContent());
      fw.close();
      return response;}catch(Exception e){return request;}


   }
}

你像SEI一样发布它,

public class ServerJSFB {

    protected ServerJSFB() throws Exception {
        System.out.println("Starting Server");
        System.out.println("Starting SoapService1");

        Object implementor = new Provider1();//create implementor
        String address = "http://localhost:8123/SoapContext/SoapPort1";

        JaxWsServerFactoryBean svrFactory = new JaxWsServerFactoryBean();//create serverfactorybean

        svrFactory.setAddress(address);
        svrFactory.setServiceBean(implementor);

        svrFactory.create();//create the server. equivalent to publishing the endpoint
        System.out.println("Starting SoapService1");
  }

public static void main(String args[]) throws Exception {
    new ServerJSFB();
    System.out.println("Server ready...");

    Thread.sleep(10 * 60 * 1000);
    System.out.println("Server exiting");
    System.exit(0);
}
}

或者您可以使用Endpoint类。希望对你有所帮助。

哦,如果你想要你不需要处理标题和东西,如果你将服务模式更改为PAYLOAD(你只会得到肥皂体)。


1
投票

此处列出的指导您使用SOAPHandler的答案是完全正确的。这种方法的好处是它可以与任何JAX-WS实现一起使用,因为SOAPHandler是JAX-WS规范的一部分。但是,SOAPHandler的问题在于它隐式尝试在内存中表示整个XML消息。这可能会导致大量内存使用。 JAX-WS的各种实现为此添加了自己的解决方法。如果您处理大型请求或大型响应,那么您需要研究一种专有方法。

由于您询问“JDK 1.5或更高版本中包含的内容”,我将回答有关正式称为JAX-WS RI(又称Metro)的内容,这是JDK中包含的内容。

JAX-WS RI有一个特定的解决方案,在内存使用方面非常有效。

https://javaee.github.io/metro/doc/user-guide/ch02.html#efficient-handlers-in-jax-ws-ri。不幸的是,这个链接现在已被破坏,但您可以在WayBack Machine上找到它。我将在下面给出重点:

地铁人员在2007年introduced回来了一个额外的处理程序类型MessageHandler<MessageHandlerContext>,它是Metro专有的。它比SOAPHandler<SOAPMessageContext>更有效,因为它不会尝试进行内存中的DOM表示。

这是原始博客文章中的重要文本:

的MessageHandler:

利用JAX-WS规范提供的可扩展Handler框架和RI中更好的Message抽象,我们引入了一个名为MessageHandler的新处理程序来扩展您的Web Service应用程序。 MessageHandler类似于SOAPHandler,除了它的实现可以访问MessageHandlerContext(MessageContext的扩展)。通过MessageHandlerContext,可以访问Message并使用Message API处理它。当我放入博客的标题时,这个处理程序允许您使用Message,它提供了访问/处理消息的有效方法,而不仅仅是基于DOM的消息。处理程序的编程模型是相同的,Message处理程序可以与标准的Logical和SOAP处理程序混合使用。我在JAX-WS RI 2.1.3中添加了一个示例,显示了使用MessageHandler来记录消息,以下是示例中的一个片段:

public class LoggingHandler implements MessageHandler<MessageHandlerContext> {
    public boolean handleMessage(MessageHandlerContext mhc) {
        Message m = mhc.getMessage().copy();
        XMLStreamWriter writer = XMLStreamWriterFactory.create(System.out);
        try {
            m.writeTo(writer);
        } catch (XMLStreamException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean handleFault(MessageHandlerContext mhc) {
        ..... 
        return true;
    }

    public void close(MessageContext messageContext) {    }

    public Set getHeaders() {
        return null;
    }
}

(最终引自2007年博文)

不用说,您的自定义处理程序,示例中的LoggingHandler,需要添加到您的处理程序链中才能产生任何效果。这与添加任何其他Handler相同,因此您可以在此页面上查看other answers以了解如何执行此操作。

你可以在full example找到一个Metro GitHub repo


1
投票

使用logback.xml配置文件,您可以执行以下操作:

<logger name="com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe" level="trace" additivity="false">
    <appender-ref ref="STDOUT"/>
</logger>

这将记录请求和响应(取决于您的日志输出配置):

09:50:23.266 [qtp1068445309-21] DEBUG c.s.x.i.w.t.h.c.HttpTransportPipe - ---[HTTP request - http://xyz:8081/xyz.svc]---
Accept: application/soap+xml, multipart/related
Content-Type: application/soap+xml; charset=utf-8;action="http://xyz.Web.Services/IServiceBase/GetAccessTicket"
User-Agent: JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e
<?xml version="1.0" ?><S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope">[CONTENT REMOVED]</S:Envelope>--------------------

09:50:23.312 [qtp1068445309-21] DEBUG c.s.x.i.w.t.h.c.HttpTransportPipe - ---[HTTP response - http://xyz:8081/xyz.svc - 200]---
null: HTTP/1.1 200 OK
Content-Length: 792
Content-Type: application/soap+xml; charset=utf-8
Date: Tue, 12 Feb 2019 14:50:23 GMT
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">[CONTENT REMOVED]</s:Envelope>--------------------

0
投票

一种方法是不使用你的代码,而是使用像Etheral或WireShark这样的网络数据包嗅探器,它可以捕获带有XML消息的HTTP数据包作为有效负载,你可以继续将它们记录到文件中。

但更复杂的方法是编写自己的消息处理程序。你可以看看它here


0
投票

其实。如果你查看HttpClientTransport的源代码,你会发现它也在将消息写入java.util.logging.Logger。这意味着您也可以在日志中看到这些消息。

例如,如果您使用的是Log4J2,则只需执行以下操作:

  • 将JUL-Log4J2桥添加到类路径中
  • 为com.sun.xml.internal.ws.transport.http.client包设置TRACE级别。
  • 将-Djava.util.logging.manager = org.apache.logging.log4j.jul.LogManager系统属性添加到您的应用程序启动命令行

完成这些步骤后,您将开始在日志中看到SOAP消息。


0
投票

我一直试图找到一些框架库来记录Web服务soap请求和响应几天。下面的代码为我解决了这个问题:

System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true");
        System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
        System.setProperty("com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump", "true");
        System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dump", "true");

78
投票

这是原始代码中的解决方案(由于stjohnroe和Shamik而放在一起):

Endpoint ep = Endpoint.create(new WebserviceImpl());
List<Handler> handlerChain = ep.getBinding().getHandlerChain();
handlerChain.add(new SOAPLoggingHandler());
ep.getBinding().setHandlerChain(handlerChain);
ep.publish(publishURL);

SOAPLoggingHandler的位置(从链接的示例中删除):

package com.myfirm.util.logging.ws;

import java.io.PrintStream;
import java.util.Map;
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

/*
 * This simple SOAPHandler will output the contents of incoming
 * and outgoing messages.
 */
public class SOAPLoggingHandler implements SOAPHandler<SOAPMessageContext> {

    // change this to redirect output if desired
    private static PrintStream out = System.out;

    public Set<QName> getHeaders() {
        return null;
    }

    public boolean handleMessage(SOAPMessageContext smc) {
        logToSystemOut(smc);
        return true;
    }

    public boolean handleFault(SOAPMessageContext smc) {
        logToSystemOut(smc);
        return true;
    }

    // nothing to clean up
    public void close(MessageContext messageContext) {
    }

    /*
     * Check the MESSAGE_OUTBOUND_PROPERTY in the context
     * to see if this is an outgoing or incoming message.
     * Write a brief message to the print stream and
     * output the message. The writeTo() method can throw
     * SOAPException or IOException
     */
    private void logToSystemOut(SOAPMessageContext smc) {
        Boolean outboundProperty = (Boolean)
            smc.get (MessageContext.MESSAGE_OUTBOUND_PROPERTY);

        if (outboundProperty.booleanValue()) {
            out.println("\nOutbound message:");
        } else {
            out.println("\nInbound message:");
        }

        SOAPMessage message = smc.getMessage();
        try {
            message.writeTo(out);
            out.println("");   // just to add a newline
        } catch (Exception e) {
            out.println("Exception in handler: " + e);
        }
    }
}

52
投票

在启动tomcat之前,在Linux envs中将JAVA_OPTS设置如下。然后启动Tomcat。您将在catalina.out文件中看到请求和响应。

export JAVA_OPTS="$JAVA_OPTS -Dcom.sun.xml.ws.transport.http.client.HttpTransportPipe.dump=true"

14
投票

设置以下系统属性,这将启用xml日志记录。您可以在java或配置文件中设置它。

static{
        System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true");
        System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
        System.setProperty("com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump", "true");
        System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dump", "true");
        System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dumpTreshold", "999999");
    }

控制台日志:

INFO: Outbound Message
---------------------------
ID: 1
Address: http://localhost:7001/arm-war/castService
Encoding: UTF-8
Http-Method: POST
Content-Type: text/xml
Headers: {Accept=[*/*], SOAPAction=[""]}
Payload: xml
--------------------------------------
INFO: Inbound Message
----------------------------
ID: 1
Response-Code: 200
Encoding: UTF-8
Content-Type: text/xml; charset=UTF-8
Headers: {content-type=[text/xml; charset=UTF-8], Date=[Fri, 20 Jan 2017 11:30:48 GMT], transfer-encoding=[chunked]}
Payload: xml
--------------------------------------

10
投票

如其他答案中所述,有多种方式可以以编程方式执行此操作,但它们是非常具有侵入性的机制。但是,如果您知道您正在使用JAX-WS RI(也称为“Metro”),那么您可以在配置级别执行此操作。 See here for instructions如何做到这一点。无需弄乱您的应用程序。


9
投票

//此解决方案提供了一种以编程方式将处理程序添加到没有XML配置的Web服务客户端的方法

//请参阅完整的文档:http://docs.oracle.com/cd/E17904_01//web.1111/e13734/handlers.htm#i222476

//创建实现SOAPHandler的新类

public class LogMessageHandler implements SOAPHandler<SOAPMessageContext> {

@Override
public Set<QName> getHeaders() {
    return Collections.EMPTY_SET;
}

@Override
public boolean handleMessage(SOAPMessageContext context) {
    SOAPMessage msg = context.getMessage(); //Line 1
    try {
        msg.writeTo(System.out);  //Line 3
    } catch (Exception ex) {
        Logger.getLogger(LogMessageHandler.class.getName()).log(Level.SEVERE, null, ex);
    } 
    return true;
}

@Override
public boolean handleFault(SOAPMessageContext context) {
    return true;
}

@Override
public void close(MessageContext context) {
}
}

//以编程方式添加Logo MessageHandler

   com.csd.Service service = null;
    URL url = new URL("https://service.demo.com/ResService.svc?wsdl");

    service = new com.csd.Service(url);

    com.csd.IService port = service.getBasicHttpBindingIService();
    BindingProvider bindingProvider = (BindingProvider)port;
    Binding binding = bindingProvider.getBinding();
    List<Handler> handlerChain = binding.getHandlerChain();
    handlerChain.add(new LogMessageHandler());
    binding.setHandlerChain(handlerChain);

7
投票

SOAPHandler注入端点接口。我们可以跟踪SOAP请求和响应

使用Programmatic实现SOAPHandler

ServerImplService service = new ServerImplService();
Server port = imgService.getServerImplPort();
/**********for tracing xml inbound and outbound******************************/
Binding binding = ((BindingProvider)port).getBinding();
List<Handler> handlerChain = binding.getHandlerChain();
handlerChain.add(new SOAPLoggingHandler());
binding.setHandlerChain(handlerChain);

通过将@HandlerChain(file = "handlers.xml")注释添加到端点接口来声明。

handlers.xml

<?xml version="1.0" encoding="UTF-8"?>
<handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
    <handler-chain>
        <handler>
            <handler-class>SOAPLoggingHandler</handler-class>
        </handler>
    </handler-chain>
</handler-chains>

SOAP logging handler.Java

/*
 * This simple SOAPHandler will output the contents of incoming
 * and outgoing messages.
 */


public class SOAPLoggingHandler implements SOAPHandler<SOAPMessageContext> {
    public Set<QName> getHeaders() {
        return null;
    }

    public boolean handleMessage(SOAPMessageContext context) {
        Boolean isRequest = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (isRequest) {
            System.out.println("is Request");
        } else {
            System.out.println("is Response");
        }
        SOAPMessage message = context.getMessage();
        try {
            SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
            SOAPHeader header = envelope.getHeader();
            message.writeTo(System.out);
        } catch (SOAPException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return true;
    }

    public boolean handleFault(SOAPMessageContext smc) {
        return true;
    }

    // nothing to clean up
    public void close(MessageContext messageContext) {
    }

}

4
投票

我发布了一个新的答案,因为我没有足够的声誉评论Antonio提供的那个(参见:https://stackoverflow.com/a/1957777)。

如果您希望将SOAP消息打印在文件中(例如通过Log4j),您可以使用:

OutputStream os = new ByteArrayOutputStream();
javax.xml.soap.SOAPMessage soapMsg = context.getMessage();
soapMsg.writeTo(os);
Logger LOG = Logger.getLogger(SOAPLoggingHandler.class); // Assuming SOAPLoggingHandler is the class name
LOG.info(os.toString());

请注意,在某些情况下,方法调用writeTo()可能不会按预期运行(请参阅:https://community.oracle.com/thread/1123104?tstart=0https://www.java.net/node/691073),因此以下代码将执行此操作:

javax.xml.soap.SOAPMessage soapMsg = context.getMessage();
com.sun.xml.ws.api.message.Message msg = new com.sun.xml.ws.message.saaj.SAAJMessage(soapMsg);
com.sun.xml.ws.api.message.Packet packet = new com.sun.xml.ws.api.message.Packet(msg);
Logger LOG = Logger.getLogger(SOAPLoggingHandler.class); // Assuming SOAPLoggingHandler is the class name
LOG.info(packet.toString());

2
投票

您需要实现一个javax.xml.ws.handler.LogicalHandler,然后需要在处理程序配置文件中引用此处理程序,而该处理程序配置文件又由服务端点(接口或实现)中的@HandlerChain批注引用。然后,您可以通过system.out输出消息,也可以在processMessage实现中输出记录器。

看到

http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=/com.ibm.websphere.express.doc/info/exp/ae/twbs_jaxwshandler.html

http://java.sun.com/mailers/techtips/enterprise/2006/TechTips_June06.html

© www.soinside.com 2019 - 2024. All rights reserved.