Setting headers on HttpServletResponse after writing response body

谁说我不能喝 提交于 2019-12-12 10:42:53

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/13536596/setting-headers-on-httpservletresponse-after-writing-response-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!