Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log request body in JAX-RS client

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.

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?


Result

The answer from @peeskillet + this snippet.

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).

like image 264
thomas.mc.work Avatar asked May 12 '15 09:05

thomas.mc.work


1 Answers

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());

Also the ClientRequestContext API for some other goodies you might find interesting.

UPDATE

See Also:

  • JAX-RS 2 print JSON request, for a complete/better implementation.
like image 130
Paul Samsotha Avatar answered Oct 20 '22 05:10

Paul Samsotha