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?