如何在JAX-RS客户端中记录请求正文 [英] How to log request body in JAX-RS client
问题描述
我需要查看带有客户端JAX-RS请求的请求主体,以验证序列化工作是否正确,并将请求重新用于测试客户端,例如邮递员.
I need to see my request body with a client JAX-RS request in order to verify that the serialization works correct and reuse the request for test clients like Postman.
我知道可以使用例如resource.addFilter(new com.sun.jersey.api.client.filter.LoggingFilter());
的Jersey激活日志记录.但是,我不直接使用Jersey或RESTEasy实现,而是通过JAX-RS API进行抽象:
I know it's possible to activate logging with Jersey using for example resource.addFilter(new com.sun.jersey.api.client.filter.LoggingFilter());
. However, I don't use Jersey or RESTEasy implementation directly, but abstracted via JAX-RS API:
final WebTarget target =
ClientBuilder.newBuilder().build().target("http://localhost:8080");
如何在此处启用日志记录?
How can I enable logging here?
@peeskillet的答案 + 但是,有时JAX-RS实现不会调用摘录中的close()
方法(在本例中为org.jboss.resteasy:resteasy-client-3.0.11.FINAL
).
However sometimes the close()
method from the snippet is not being invoked by the JAX-RS implementation (org.jboss.resteasy:resteasy-client-3.0.11.FINAL
in this case).
推荐答案
JAX-RS 2.0 (which it looks like you're using), has the ClientRequestFilter
. You can register it with the Client
or even the WebTarget
. From the filter
method, you can get the entity, and do your logging
public class LoggingFilter implements ClientRequestFilter {
private static final Logger LOG = Logger.getLogger(LoggingFilter.class.getName());
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
LOG.log(Level.INFO, requestContext.getEntity().toString());
}
}
[...]
Client client = ClientBuilder.newClient();
client.register(new LoggingFilter());
ClientRequestContext
API a>对于其他一些东西,您可能会发现有趣.
Also the ClientRequestContext
API for some other goodies you might find interesting.
另请参见:
- JAX-RS 2打印JSON请求,以实现完整/更好的实施.
- JAX-RS 2 print JSON request, for a complete/better implementation.
这篇关于如何在JAX-RS客户端中记录请求正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!