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

查看:542
本文介绍了检测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.

我有什么方法可以忽略吗?

Is there an approach I'm overlooking?

推荐答案

假设您希望您的客户端与其他服务器一起工作,并且服务器与其他客户端一起工作,那么您的服务器将无法得到很好的处理。

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.

有两种方法可以判断身体何时结束。他们都不需要你所建议的身体内容类型的知识(例如,不要费心寻找< / 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的块检测正文的结尾。

  2. 如果客户端改为发送 Content-长度,你必须使用它。

  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天全站免登陆