zappee zappee - 6 months ago 29
Java Question

JAX-RS response filter > getLength() is always -1

I am trying to write a JAX-RS response filter to log the request and response details but responseContext.getLength() always returns with -1 despite of response has body content.

Here is my code:

@Override
public void filter(final ContainerRequestContext requestContext,
final ContainerResponseContext responseContext) throws IOException {

System.out.println(responseContext.getLength());

if (responseContext.hasEntity()) {
System.out.println(responseContext.getEntity());
}
}


Output:

-1 and "apple"

What is the correct way to log the length of the response?

Answer Source

If you look at the java-docs for the ContextResponseContext

http://docs.oracle.com/javaee/7/api/javax/ws/rs/container/ContainerResponseContext.html#getLength--

Content-Length as integer if present and valid number. In other cases returns -1.

By this, I guess it's pretty obvious why it returns -1. Can you set it in your response object?

Also, if you just want the length of your response, may be you can do: responseContext.getEntity().length()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download