2

我只是想获取带有标题的页面内容...但是对于通过的最后一个信息包来说,我的大小为 1024 的缓冲区似乎太大或太小...我不想要得到太多或太少,如果这是有道理的。这是我的代码。它可以很好地打印出包含所有信息的页面,但我想确保它是正确的。

//Build HTTP Get Request
std::stringstream ss;
ss << "GET " << url << " HTTP/1.0\r\nHost: " << strHostName << "\r\n\r\n";
std::string req = ss.str();

// Send Request
send(hSocket, req.c_str(), strlen(req.c_str()), 0);

// Read from socket into buffer.
do
{
     nReadAmount = read(hSocket, pBuffer, sizeof pBuffer);
     printf("%s", pBuffer);

}
while(nReadAmount != 0);
4

2 回答 2

2

读取 HTTP 回复的正确方法是读取直到收到完整的LF分隔行(有些服务器使用bare LF,即使官方规范说使用CRLF),其中包含响应代码和版本,然后继续阅读 LF 分隔的行,哪些是标头,直到遇到一个 0 长度的行,表示标头的结尾,然后您必须分析标头以找出剩余数据的编码方式,以便您知道读取它的正确方法并知道它是如何编码的被终止。有几种不同的可能性,有关实际规则,请参阅RFC 2616 第 4.4 节。

换句话说,您的代码需要改用这种结构(伪代码):

// Send Request
send(hSocket, req.c_str(), req.length(), 0);

// Read Response
std::string line = ReadALineFromSocket(hSocket);
int rescode = ExtractResponseCode(line);
std::vector<std::string> headers;
do
{
     line = ReadALineFromSocket(hSocket);
     if (line.length() == 0) break;
     headers.push_back(line);
}
while (true);

if (
    ((rescode / 100) != 1) &&
    (rescode != 204) &&
    (rescode != 304) &&
    (request is not "HEAD")
)
{
    if ((headers has "Transfer-Encoding") && (Transfer-Encoding != "identity"))
    {
        // read chunks until a 0-length chunk is encountered.
        // refer to RFC 2616 Section 3.6 for the format of the chunks...
    }
    else if (headers has "Content-Length")
    {
       // read how many bytes the Content-Length header says...
    }
    else if ((headers has "Content-Type") && (Content-Type == "multipart/byteranges"))
    {
        // read until the terminating MIME boundary specified by Content-Type is encountered...
    }
    else
    {
        // read until the socket is disconnected...
    }
}
于 2013-01-20T03:50:25.260 回答
2
 nReadAmount = read(hSocket, pBuffer, sizeof pBuffer);
 printf("%s", pBuffer);

这已破了。您只能将%s格式说明符用于 C 样式(以零结尾)字符串。应该如何printf知道要打印多少字节?该信息在 中nReadAmount,但您不使用它。

printf此外,即使read失败,您也会打电话。

最简单的修复:

 do
 {
     nReadAmount = read(hSocket, pBuffer, (sizeof pBuffer) - 1);
     if (nReadAmount <= 0)
         break;
     pBuffer[nReadAmount] = 0;
     printf("%s", pBuffer);
 } while(1);
于 2013-01-20T02:37:45.997 回答