带套接字的POST请求

时间:2012-04-15 04:22:09

标签: c++ sockets http-headers http-post

我必须在c ++中使用纯套接字发送post-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;
}

但在buf发送身体后我有:

<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx</center>
</body>
</html>

这里可能有什么问题?


UPD

由于您的评论我写的新标题:

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;

还有同样的问题。


UPD2

使用此命令:curl -s -v -X POST 'http://0.0.0.0/push1_pub?id=game' -d 'Test'一切正常,生成后发送请求。

1 个答案:

答案 0 :(得分:2)

您的主机线错了。它应该是一个简单的主机名,例如“localhost”或“example.com”,而不是您现在拥有的http://0.0.0.0:80网址。

网络服务器使用主机线来识别正在请求在单个IP上托管的几千个站点中的哪些站点。端口号也没用,因为当您发送HTTP头时,TCP连接已经建立。由于您已经在执行HTTP请求,因此无需冗余地指定正在使用的协议。

相关问题