简体   繁体   中英

Setting headers on HttpServletResponse after writing response body

I figured out the hard way that it isn't possible to add more headers to an HttpServletResponse after beginning to write the response body to the output buffer, which, I guess in some random universe could make sense even though everything is still just buffered in memory.

Now the question is: Is there some trick to circumvent this somehow? Clearly, since the function resetBuffer() is available, which allows clearing of the content body without clearing the headers, there must be some way for the HttpServletResponse object to return to the state where writing more headers was possible. Is there, for example, a way to read the content body, clearing it with resetBuffer() , setting more headers, and then restoring the content body?

Aside : The reason I would like do this is so I can add a header as the preferably very last step in my servlet, which tells me how long the server was busy processing the request.

Your only choice is to buffer the response body yourself; when body is finished, you then add the header, then write the body.

The funny thing is, HTTP/1.1 has a way to ship a header after the response body, by using trailer in chunked encoding, but nobody implements that, so don't bother.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM