0

I'm trying to send a GET request to a webserver(example: www.coursera.org,...). But sServer returns a response header: HTTP/1.1 400 bad request

I used Winsock in C++ and establish a socket connect to server. Then, send a GET request to server.

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();

}

The problem seems to be GET request that is wrong?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
hugtech
  • 877
  • 3
  • 11
  • 16

1 Answers1

2

They can't parse your request because you are trying to send it to https port (443) unencrypted. You can try to send it http port (80), but they will redirect you to https://coursera.org anyway.

grungegurunge
  • 841
  • 7
  • 13
  • I sent to port(80) and receive a error "301 Moved Permanently". I think that port 80 is used when website have http protocol and port 443 for https protocol. – hugtech Jan 07 '19 at 10:06
  • 1
    Yes, that's correct. In other words, they tell you that they do not support HTTP, only HTTPS. So, to work with them, you need to support HTTPS in your application. – grungegurunge Jan 07 '19 at 10:09
  • Yes. I have just realized this. When using port 80, The code is ok with HTTP websites. But toward HTTPS, it is not ! Thank you ! – hugtech Jan 07 '19 at 10:42