PKM
PKM

Reputation: 329

Setting content length in http response object after writing to its OutputStream

I have a handler in a jetty server deployment, which has a reference to the HttpServletResponse object.

I am writing byte content to the Response.getOutputStream() like below:

ServletOutputStream serlvetOutputStream = handlerContext.getResponse().getOutputStream();
...
while(condition) { 
//read chunk from some source into byteBuffer
servletOutputStream.write(byteBuffer, 0, lengthRead);
}

But before I can write write(), I must set the content-length the http client expects in the response:

handlerContext.getResponse().setContentLength((int) length); //or as below
handlerContext.getResponse().addHeader("Content-Length", String.valueOf(length));

Failure to set the length before writing to the outputstream, results in an "Error File size unknown" popup box on the Windows client application. But in some cases, I would not know what would be the length to be written until afterward. I cannot accumulate the entire data to be read beforehand (because it can time-out the client for larger data) so it must be "chunked" i.e read x kilobytes and then write x kilobytes, until condition is false.

My question is - is there any way to dynamically update the content length just before writing? In the loop above, I want to set the content-length as however many bytes were available to write, write() those, and then update it again when it loops around.

If I update the content-length within the loop, I get jetty.server.EoFexception.

Upvotes: 2

Views: 5814

Answers (1)

user207421
user207421

Reputation: 311052

You don't need to set the content length. It will happen automatically. What you have here is an XY problem. You have an undisclosed exception and you think that setting the content length will solve it. However, as you can't set the content length either, you have zero actual evidence for your belief.

Upvotes: 2

Related Questions