Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 229
Markus A. Avatar asked Nov 23 '12 22:11

Markus A.


People also ask

How do you set a response header?

Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.

Can we set response header?

You can set response headers, you can add response headers And you can wonder what the difference is. But think about it for a second, then do this exercise. Draw a line from the HttpResponse method to the method's behavior.

How do I get response header responses?

View headers with browser development toolsSelect the Network tab. You may need to refresh to view all of the requests made for the page. Select a request to view the corresponding response headers.


1 Answers

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.

like image 105
irreputable Avatar answered Oct 24 '22 23:10

irreputable