I need to stream a response from a Jersey resource but I don't want the http response to use Transfer-Encoding: chunked. I know the length of the stream ahead of time so chunked encoding should not be necessary.
@GET
@Path("/contentLength")
public Response contentLength() {
return Response.ok()
.header("Content-Length", 10_000)
.entity(RandomInputStream.generateBytes(10_000))
.build());
}
Even tho I've set Content-Length a test shows that the response uses chunked transfer encoding
@Test
void contentLength() throws Exception {
Response response = target().path("/contentLength").request().get();
assertThat(response.getHeaderString("Transfer-Encoding"), Matchers.nullValue());
assertThat(response.getHeaderString("Content-Length"), is("10000"));
}
Expected: null
but: was "chunked"
There are similar questions but the answers are wrong or require buffering the response which is not feasible for large responses. Chunked encoding is not required by http for large responses, it is only required when the total length is not known when the response is started.