我有一个小程序发送HTTP请求并获取响应与TCP协议。
我请求格式;
GET / HTTP/1.0
Host: somewebsite.com
{two new line}
我从插座(使用C#中的NetworkStream和StreamReader的),直到找到要找的内容长度报头读取响应一行一行。 我店的长度,然后继续读,直到找到一个空行。 然后创建具有长度的缓冲器和接收响应的其余部分。
但是,一些反应变量没有一个Content-Length头。 所以我的方法失败。 如果我不知道我应该有多少个字节接收,当我应该停止?
See relevant part of HTTP spec.
In your specific case, if the server does not give content length back, then it MUST be closing the stream upon finishing the response. There is no other reliable way for you (as a client) to know. Regardless of HTTP version. @Julian chunked encoding is indeed a clever upgrade in HTTP/1.1 but is rather specific to streaming and there is no reason why a "plain" webserver would implement it. That is a server which knows the content length before initiating response. And i guess that the OP doesn't have the server under control, otherwise he won't be objecting missing HTTP headers.
But even if you DO get the content length header, you must not unreservedly trust it. The server implementors are only fallible humans too. Take it as a "most probable" response, initial value to a resizable buffer. You still must be ready to handle less as well as more (the worse case).