通过使用WinSock库发送GET HTTP请求时,400坏请求错误(400 bad request

2019-10-29 12:38发布

我试图发送一个GET请求到网络服务器(例如:www.coursera.org,...)。 但sServer返回响应标头: HTTP/1.1 400 bad request

我使用Winsock的C ++和建立一个套接字连接到服务器。 然后,发送一个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请求,这是错误的?

Answer 1:

因为你试图将它发送到HTTPS端口(443)未加密的,他们不能分析你的要求。 你可以尝试将其发送HTTP端口(80),但他们会为您重定向到https://coursera.org反正。



文章来源: 400 bad request error when send a GET http request by using winsock library