gpt4 book ai didi

c++ - 错误套接字更新 C++

转载 作者:行者123 更新时间:2023-11-28 05:55:03 24 4
gpt4 key购买 nike

我正在尝试实现一个 http get 请求。但是响应不好,我没有收到get请求内容。

我有以下代码:

WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cout << "WSAStartup failed.\n";
system("pause");
return 1;
}
SOCKET Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct hostent *host;
host = gethostbyname("www.httpbin.org");
SOCKADDR_IN SockAddr;
SockAddr.sin_port = htons(80);
SockAddr.sin_family = AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
std::cout << "Connecting...\n";
if (connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr)) != 0){
std::cout << "Could not connect";
system("pause");
return 1;
}
std::cout << "Connected.\n";
const char* httpRequest = "GET / HTTP/1.1\r\nHost:www.httpbin.org/get\r\nConnection: close\r\n\r\n";
send(Socket, httpRequest, strlen(httpRequest), 0);
char buffer[10000];
int nDataLength;
while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0){
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
std::cout << buffer[i];
i += 1;
}
}
closesocket(Socket);
WSACleanup();
system("pause");
return 0;

我不明白为什么我会收到这个:

HTTP/1.1 400 Bad Request
Server: nginx
Date: Thu, 17 Dec 2015 20:49:05 GMT
Connection: close
Content-Type: text/html
Content-Length: 166

<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx</center>
</body>
</html>

如果我输入 google.com 就可以了。我想念什么?所以我的第一个问题是错误是什么。第二个问题是在此代码中添加什么以获取文件。

我替换这一行:

"GET file.txt / HTTP/1.1\r\nHost:www.httpbin.org/get\r\nConnection: close\r\n\r\n"

但它不起作用。

最佳答案

将您的请求字符串更改为此 -->

"GET /get\r\nHost:www.httpbin.org\r\n\r\n"

 "GET /get\r\nHost:www.httpbin.org\r\nConnection: close\r\n\r\n"

关于c++ - 错误套接字更新 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34344028/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com