检测 HTTP 请求正文的结尾 [英] Detect end of HTTP request body

查看:37
本文介绍了检测 HTTP 请求正文的结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写自己的 HTTP 客户端和服务器,并希望客户端在请求中包含一个可选的正文.在服务器端,我想在发送 HTTP 响应之前读取整个正文.我的问题是在服务器上我怎么知道我已经阅读了整个正文?

I'm playing around with writing my own HTTP client and server and want to have the client include an optional body in the request. On the server side I want to read the entire body before sending the HTTP response. My question is on the server how do I know that I've read the entire body?

即使在这种情况下我控制客户端和服务器,我也在寻找一种标准"方法.但是,由于 Content-Length 是可选的,我想要一个不需要它的方法.如果客户端关闭连接,很容易读取所有可用数据,但是客户端需要保持连接打开等待响应,因此该方法不起作用.

Even though in this case I control both the client and server, I'm looking for a "standard" approach. However, since Content-Length is optional I want a method that doesn't require it. If the client closes the connection, it is easy to read all available data, however the client needs to keep the connection open to wait for a response, so this method doesn't work.

我能想到的就是了解正文的格式并检测终止符(例如</HTML>).理想情况下,我不想要求这些知识.

All that I can think I'm left with is having knowledge of the format of the body and detecting a terminator (eg. </HTML>). Ideally I'm not wanting to require that knowledge.

有没有我忽略的方法?

推荐答案

假设您希望您的客户端与其他服务器一起工作,并且服务器与其他客户端一起工作,那么您的服务器不能期望得到很好的对待.

Assuming you want your client to work with other servers, and server to work with other clients, your server can't expect to be treated nicely.

有两种方法可以判断 body 何时结束.它们都不需要您建议的正文内容类型的知识(例如,不要费心寻找 </html> - 这远远超出了 HTTP 协议).

There are two ways to tell when the body has ended. Neither of them require knowledge of the body's content type as you suggest (e.g., don't bother looking for </html> -- that goes far outside the HTTP protocol).

  1. 如果客户端发送带有 Transfer-Encoding: Chunked 的消息,您将需要解析有些复杂的 分块传输编码语法.在这件事上你真的没有太多选择——如果客户端以这种格式发送,你必须接收它.客户端使用这种方式时,可以通过一个长度为0的chunk来检测body的结尾.
  2. 如果客户端发送的是 Content-Length,您必须使用它.
  1. If the client sends a message with Transfer-Encoding: Chunked, you will need to parse the somewhat complicated chunked transfer encoding syntax. You don't really have much choice in the matter -- if the client is sending in this format, you have to receive it. When the client is using this approach, you can detect the end of the body by a chunk with a length of 0.
  2. If the client instead sends a Content-Length, you must use that.

正如您所建议的,第三种检测结束的方法——当连接关闭时——仅适用于响应,而不适用于请求(因为那时无法发送响应).

As you suggest, the third method for detecting the end -- when the connection closes -- only works for the response, not the request (as then there is no way to send a response).

这篇关于检测 HTTP 请求正文的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆