我在套接字上发出了一个 http GET 请求,但遇到了一个问题:我怎样才能提前知道来自服务器的响应的长度以及是否有必要?这是请求(响应)代码:
bool SendHttpGETRequest(LPCSTR PTFWP, LPCSTR site)
{
string get = "GET "s + PTFWP + " HTTP/1.1\r\nHost: " + site + "\r\nConnection: close\r\n\r\n";
if (send(servSock, get.c_str(), get.size(), 0) <= 0) {
result = "Error\0";
return false;
}
char* resHeaders = new char[310];
if (recv(servSock, resHeaders, 310, 0) < 0) {
result = "Error!\0";
return false;
}
result = resHeaders;
result = result.substr(result.find("Content-Length:") + 15);
result = result.substr(0, result.find_first_of("\r\n"));
int bufSize = stoi(result);
delete resHeaders;
resHeaders = new char[bufSize + 1];
int readOfBytes = 0;
int AllSize = 0;
result = "";
while (((readOfBytes = recv(servSock, resHeaders, bufSize, 0)) > 0) && ((AllSize+=readOfBytes)<= bufSize)) {
result += resHeaders;
}
result[bufSize] = '\0';
if ((readOfBytes < 0) && result.empty())
return false;
return true;
}