Jersey/JAX-RS : Return Content-Length in response header instead of chunked transfer encoding

java, jax-rs, jaxb, jersey, rest

Solution

Selecting `Content-Length` or `Transfer-Encoding` is just those Containers choice. It's really a matter of buffer size.

One possible solution is providing a `SevletFilter` which buffers all those marshalled bytes and sets `Content-Length` header value.

See this page.

@WebFilter
public class BufferFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
        throws IOException, ServletException {

        final ByteArrayOutputStream buffer =
            new ByteArrayOutputStream();

        // prepare a new ServletResponseWrapper
        // which returns the buffer as its getOutputStream();

        chain.doFilter(...)

        // now you know how exactly big is your response.

        final byte[] responseBytes = buffer.toByteArray();
        response.setContentLength(responseBytes.length);
        response.getOutputStream().write(responseBytes);
        response.flush();
    }

    @Override
    public void destroy() {
    }
}

Problem

I'm using Jersey to create RESTful API resources, and `ResponseBuilder` to generate the response. Example code for the RESTful resource: ``` public class infoResource{ @GET @Path("service/{id}") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response getCompany(@PathParam("id")String id) { //company is just a POJO. Company company = getCompany(id); return Response.status(200).entity(company).build(); } } ``` In the response, it's returning chunked transfer encoding in the response headers. What is the proper way in the "Jersey world" to have it return the `Content-Length` header instead of the `Transfer-Encoding: chunked` header in the response headers?

Original source