我正在尝试将GET请求发送到网络服务器(例如:www.coursera.org,...)。但是sServer返回一个响应头:HTTP/1.1 400 bad request
我在C ++中使用Winsock并建立了一个连接服务器的套接字。然后,将GET请求发送到服务器。
int main(void) {
get_Website("www.coursera.org");
cout << website_HTML;
cout << "\n\nPress ANY key to close.\n\n";
cin.ignore(); cin.get();
return 0;
}
void get_Website(string url)
{
WSADATA wsaData;
SOCKET Socket;
SOCKADDR_IN SockAddr;
int lineCount = 0;
int rowCount = 0;
struct hostent* localHost;
string srequete;
char* localIP;
srequete = "GET / HTTP/1.0\r\n";
srequete += "Host: www.coursera.org\r\n";
srequete += "Connection: close\r\n\r\n";
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
cout << "WSAStartup failed.\n";
system("pause");
//return 1;
}
Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
localHost = gethostbyname(url.c_str());
localIP = inet_ntoa(*(struct in_addr *)*localHost->h_addr_list);
SockAddr.sin_port = htons(443);
SockAddr.sin_family = AF_INET;
SockAddr.sin_addr.s_addr = inet_addr(localIP);
if (connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr)) != 0) {
cout << "Could not connect";
system("pause");
//return 1;
}
send(Socket, srequete.c_str(), strlen(srequete.c_str()), 0);
int nDataLength;
while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0) {
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
website_HTML += buffer[i];
i += 1;
}
}
closesocket(Socket);
WSACleanup();
}
问题似乎是错误的GET请求?
答案 0 :(得分:2)
他们无法解析您的请求,因为您试图将其发送到未加密的https端口(443)。您可以尝试将其发送为http端口(80),但无论如何它们都会将您重定向到https://coursera.org。