24

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

Community
  • 1
  • 1
thomas.mc.work
  • 6,404
  • 2
  • 26
  • 41

1 Answers1

38

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:

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • 4
    That works basically, however the the method `requestContext.getEntity()` returns the Entity as object before the serialization happens. Is there a way to get the plain text body that will be sent? – thomas.mc.work May 18 '15 at 13:59
  • The background is that I try to utilize both the library `jackson-datatype-joda` and a custom Jackson-MixIn. I want to see the serialized output to prove the serialization called by JAX-RS works right. – thomas.mc.work May 18 '15 at 14:18
  • You might need to marshal the object yourself inside the filter. Only easy way I can think of. Kinda doubles the workload though. There might be other ways, but it's not really something I have explored. – Paul Samsotha May 18 '15 at 14:40
  • I've found [this solution](http://1987.io/questions/3342335/get-request-body-of-my-request) which works basically although not looking too elegant – thomas.mc.work May 18 '15 at 15:04
  • 4
    The site is no longer available... could you share what you found? – tytk Jan 10 '16 at 05:43
  • @thomas.mc.work it's also not available on archive.org – hiergiltdiestfu Jan 27 '17 at 15:55
  • Sorry, I can't rmemeber what I've found there anymore. My fault to post only the link instead of the core content. – thomas.mc.work Jan 30 '17 at 10:00