2

How do I get the actual body of request I am about to do?

    Invocation i = webTarget.path("somepath")
    .request(MediaType.APPLICATION_JSON)
    .buildPut(Entity.entity(account, MediaType.APPLICATION_JSON));
    log.debug(i.... ); // I want to log the request
2

2 Answers 2

2

You could try to wrap the Outputstream for the Entity. First, by using a javax.ws.rs.client.ClientRequestFilter to add a custom Outputstream to the ClientRequestContext.

Client client = ClientBuilder.newClient().register(MyLoggingFilter.class);

public class MyLoggingOutputStreamWrapper extends OutputStream{
  static final Logger logger = Logger.getLogger(...);
  ByteArrayOutputStream myBuffer = new ...
  private OutputStream target;

  public MyLoggingOutputStreamWrapper(OutputStream target){ ...

  // will be smarter to implement write(byte [], int, int) and call it from here 
  public void write(byte [] data){
    myBuffer.write(data);
    target.write(data);
  }

  ... // other methods to delegate to target, especially the other write method

  public void close(){
    // not sure, if converting the buffer to a string is enough. may be in a different encoding than the platform default
    logger.log(myBuffer.toString());
    target.close();
  }
}

@Provider
public class MyLoggingFilter implements ClientRequestFilter{
  // implement the ClientRequestFilter.filter method
  @Override
  public void filter(ClientRequestContext requestContext) throws IOException {
     requestContext.setEntityOutputstream(new MyLoggingOutputStreamWrapper(requestContext.getEntityOutputstream()));
  }

I'm not sure at which point the outputstream is used to serialize the data. It could be at the moment you invoke buildPut(), but more likely it will be on the fly at access of the webclient.

Another approach would be getting the underlying HttpClient and registering some listener there to get the body.

1
  • This doesn't appear to work at all. The customized OutputStream is never written to, likely because the body has already been written.
    – BadZen
    Jun 7, 2017 at 23:01
0

I had a similar problem. I couldn't use the Jersey LoggingFilter (and the new LoggingFeature in 2.23) because I needed to customize the output. For using the other options you can see this post: Jersey: Print the actual request

I've simplified what I did for brevity. It is pretty similar to the original answer, but I adapted the Jersey LoggingStream (it is an internal class you can't access) and took out the ability to log up to a maximum size.

You have a class that extends the OutputStream so you can capture the entity in it. It will write to your OutputStream as well as the original.

public class MyLoggingStream extends FilterOutputStream
{
private final ByteArrayOutputStream baos = new ByteArrayOutputStream();

public MyLoggingStream(final OutputStream inner)
{
    super(inner);
}

public String getString(final Charset charset)
{
    final byte[] entity = baos.toByteArray();
    return new String(entity, charset);
}

@Override
public void write(final int i) throws IOException
{
    baos.write(i);
    out.write(i);
}
}

Then you have a filter class. It was important for my use case that I was able to grab the entity and log it separately (I've put it as println below for simplicity). In Jersey's LoggingFilter and LoggingFeature the entity gets logged by the Interceptor, so you can't capture it.

@Provider
public class MyLoggingClientFilter implements ClientRequestFilter, ClientResponseFilter, WriterInterceptor
{
protected static String HTTPCLIENT_START_TIME = "my-http-starttime";
protected static String HTTPCLIENT_LOG_STREAM = "my-http-logging-stream";

@Context
private ResourceInfo resourceInfo;

public void filter(final ClientRequestContext requestContext) throws IOException
{
    requestContext.setProperty(HTTPCLIENT_START_TIME, System.nanoTime());

    final OutputStream stream = new MyLoggingStream(requestContext.getEntityStream());
    requestContext.setEntityStream(stream);
    requestContext.setProperty(HTTPCLIENT_LOG_STREAM, stream);
}

public void filter(final ClientRequestContext requestContext, final ClientResponseContext responseContext)
{
    StringBuilder builder = new StringBuilder("--------------------------").append(System.lineSeparator());

    long startTime = (long)requestContext.getProperty(HTTPCLIENT_START_TIME);
    final double duration = (System.nanoTime() - startTime) / 1_000_000.0;
    builder.append("Response Time: ").append(duration);

    if(requestContext.hasEntity())
    {
        final MyLoggingStream stream = (MyLoggingStream)requestContext.getProperty(HTTPCLIENT_LOG_STREAM);
        String body = stream.getString(MessageUtils.getCharset(requestContext.getMediaType()));
        builder.append(System.lineSeparator()).append("Entity: ").append(body);
    }

    builder.append(System.lineSeparator()).append("--------------------------");
    System.out.println(builder.toString());

    requestContext.removeProperty(HTTPCLIENT_START_TIME);
    requestContext.removeProperty(HTTPCLIENT_LOG_STREAM);
}

@Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException
{
    // This forces the data to be written to the output stream
    context.proceed();
}

}

1
  • Do you need to extend WriterInterceptor and override aroundWriteTo()? It seems to be working fine without WriterInterceptor
    – ChrisO
    Jan 14, 2017 at 1:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.