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?
Selecting
Content-Length
orTransfer-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 setsContent-Length
header value.See this page.
An answer to a very similar question on StackOverflow can be found here
I've copied it here to make sure it's not converted to a comment:
A great sample filter for doing this, that can be used standalone from the project, is this ContentLengthFilter.java from the Carrot2 project on github.
Note that uses a response wrapper with a byte stream to solve the issue, so this also ensures that
Transfer-Encoding: Chunked
doesn't get set by some other Filter/code in the filter chain, and override yourContent-Length
header when it's set. You can verify that by testing this with larger files, as they'd normally be chunked in the response.I'm going to copy the contents of the file here as well, to ensure it doesn't become a broken link:
In you class that extends ResourceConfig you can set the buffer size. Responses above this size will be chunked, below will have Content-Length.
For example, if your inputstream is read from a local file system, just add:
Check the full code for a clearer explanation:
The client side is a Apache HttpClient code.