I need to send a POST request to the server and get an answer. The request is sent and the response comes Bad request 400 ... Help to make the correct request. Here is a piece of code.

int request(char* hostname, char* parameters, string& message){ WSADATA WsaData; WSAStartup(0x0101, &WsaData); sockaddr_in sin; int sock = socket(AF_INET, SOCK_STREAM, 0); if (sock == -1){ return -100; } sin.sin_family = AF_INET; sin.sin_port = htons((unsigned short)8080); struct hostent * host_addr = gethostbyname(hostname); sin.sin_addr.s_addr = *((int*)*host_addr->h_addr_list); connect(sock, (const struct sockaddr *)&sin, sizeof(sockaddr_in)); string send_str; char *sendbuf = "987"; SEND_RQ("POST cheak.php HTTP/1.1\r\n"); SEND_RQ("Host: www.exemple.com\r\n"); SEND_RQ("Referer: http://exemple.com/cheak.php\r\n"); SEND_RQ("User-Agent: Mozilla/4.0\r\n"); SEND_RQ("Accept: text/html, application/xml;q=0.9, application/xhtml+xml, */*;q=0.1\r\n"); SEND_RQ("Content-Length: 310\r\n"); SEND_RQ("Content-Type: application/x-www-form-urlencoded\r\n"); SEND_RQ("\r\n"); SEND_RQ("key=123"); cout<<"####HEADER####"<<endl; char c1[1]; int l, line_length; bool loop = true; bool bHeader = false; while (loop){ l = recv(sock, c1, 1, 0); if (l<0) loop = false; if (c1[0] == '\n'){ if (line_length == 0) loop = false; line_length = 0; if (message.find("200") != string::npos) bHeader = true; }else{ if (c1[0] != '\r'){ line_length++; } } cout << c1[0]; message += c1[0]; } message = ""; if (bHeader){ cout << "####BODY####" << endl; char p[1024 * 10]; l = recv(sock, p, 1024 * 10 - 1, 0) _DEBUG_PRINT(write(p, l)); p[l] = '\0'; message += p; cout << message.c_str(); }else{ return -102; } cout << "end"; closesocket(sock); WSACleanup(); return 0; } int main(){ string message; int a = request("exemple.com", "", message); } 
  • And why not curl, for example? - Vladimir Martyanov

2 answers 2

The path must begin with a slash, or write the full URI, i.e.

 "POST /cheak.php HTTP/1.1\r\n" 

or

 "POST http://exemple.com/cheak.php HTTP/1.1\r\n" 

In general, go to the browser or curl'om, and then copy the request from there.

    Thank. I sent a request to the page (check.php) in the browser and received a request. Who needs a request:

     SEND_RQ("POST /cheat/check.php HTTP/1.1\r\n"); SEND_RQ("Host: exemple.com\r\n"); SEND_RQ("Connection: keep-alive\r\n"); SEND_RQ("Content-Length: 81\r\n"); SEND_RQ("Origin: http://exemple.com\r\n"); SEND_RQ("User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36\r\n"); SEND_RQ("Content-Type: application/x-www-form-urlencoded\r\n"); SEND_RQ("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n"); SEND_RQ("Referer: http://exemple.com/cheat/\r\n"); SEND_RQ("Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4\r\n"); SEND_RQ("\r\n"); SEND_RQ("key=123&uu=456\r\n");