How do I report an error midway through a chunked http repsonse without closing the connection?

折月煮酒 提交于 2020-01-02 08:33:41

问题


I have an HTTP server that returns large bodies in response to POST requests (it is a SOAP server). These bodies are "streamed" via chunking. If I encounter an error midway through streaming the response how can I report that error to the client and still keep the connection open? The implementation uses a proprietary HTTP/SOAP stack so I am interested in answers at the HTTP protocol level.


回答1:


Once the server has sent the status line (the very first line of the response) to the client, you can't change the status code of the response anymore. Many servers delay sending the response by buffering it internally until the buffer is full. While the buffer is filling up, you can still change your mind about the response.

If your client has access to the response headers, you could use the fact that chunked encoding allows the server to add a trailer with headers after the chunked-encoded body. So, your server, having encountered the error, could gracefully stop sending the body, and then send a trailer that sets some header to some value. Your client would then interpret the presence of this header as a sign that an error happened.




回答2:


Also keep in mind that chunked responses can contain "footers" which are just like HTTP headers. After failing, you can send a footer such as:

X-RealStatus: 500 Some bad stuff happened

Or if you succeed:

X-RealStatus: 200 OK



回答3:


you can change the status code as long as response.iscommitted() returns false. (fot HttpServletResponse in java, im sure there exists an equivalent in other languages)



来源:https://stackoverflow.com/questions/162917/how-do-i-report-an-error-midway-through-a-chunked-http-repsonse-without-closing

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