I have to send post-request using pure sockets in c++. I can’t understand where to send the body of the request:
int *binary = new int[bufferLength];
...
std::stringstream out(data);
out << "POST /push1_pub?id=game HTTP/1.1\n";
out << "Host: http://0.0.0.0:80\n";
out << "Content-Length: ";
out << bufferLength*sizeof(int);
out << "\r\n\r\n";
out << binary;
if (socket.send(data.c_str(), data.size()) == -1)
{
std::cout << "Failed to send headers\n";
}
else
{
// Send request body
socket.send(reinterpret_cast<char*>(binary), bufferLength*sizeof(int));
// Get the answer of server
char buf[1024];
std::cout << socket.recv(buf, 1024) << std::endl;
std::cout << buf << std::endl;
}
But in buf after sending body I have:
<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx</center>
</body>
</html>
What could be wrong here?
upd:
New headers I have written due to your comments:
std::string data;
std::stringstream out(data);
out << "POST /push1_pub?id=game\r\n";
out << "Host: http://localhost\r\n";
out << "Content-Length: ";
out << bufferLength << "\r\n";
out << "\r\n\r\n";
out << binary;
Still have same problem.
upd2
With this command: curl -s -v -X POST 'http://0.0.0.0/push1_pub?id=game' -d 'Test' Everything works fine and post request is generated and sent right.
Your host line is wrong. It should be a simple hostname, e.g. “localhost” or “example.com”, not the
http://0.0.0.0:80URL you’ve got now.The host line is used by the webserver to identify which of potentially THOUSANDS of sites hosted on a single IP is being requested. The port number is also useless, since by the time you’re sending the HTTP headers, the TCP connection has already been established. And since you’re already doing an HTTP request, there’s no need to redundantly specify the protocol in use.