简体   繁体   English

提升 ASIO HTTP 客户端 POST

[英]Boost ASIO HTTP client POST

I am trying to get boost ASIO library to send a post but the variables never make it to the server.我正在尝试使用 boost ASIO 库来发送帖子,但变量从未发送到服务器。 I know the server is working properly (tested with curl)我知道服务器工作正常(用 curl 测试)

This code does not work (the variable msg is not posted to the server) but it does work when I use curl此代码不起作用(变量 msg 未发布到服务器)但是当我使用 curl 时它起作用

tcp::resolver resolver(io_service);
tcp::resolver::query query("localhost",  "3000"); // "http");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::resolver::iterator end;

tcp::socket socket(io_service);
boost::system::error_code error = boost::asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
  socket.close();
  socket.connect(*endpoint_iterator++, error);
}
if (error)
  throw boost::system::system_error(error);

boost::asio::streambuf request;
std::ostream request_stream(&request);

string sToSend = "msg=testing";

request_stream << "POST / HTTP/1.1\r\n";
request_stream << "Host: " << "localhost:3000" << "\r\n";
request_stream << "Accept: */*\r\n";
request_stream << "Content-Length: " <<  sToSend.length() << "\r\n";
request_stream << "Content-Type: application/x-www-form-urlencoded";
request_stream << "Connection: close\r\n\r\n"; d
request_stream << sToSend;

// Send the request.
boost::asio::write(socket, request);

boost::asio::streambuf response;
boost::asio::read_until(socket, response, "\r\n");

To test the server I use测试我使用的服务器

$ curl --verbose -X POST -d msg=testing123 localhost:3000/
* Hostname was NOT found in DNS cache
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 3000 (#0)
> POST / HTTP/1.1
> User-Agent: curl/7.35.0
> Host: localhost:3000
> Accept: */*
> Content-Length: 14
> Content-Type: application/x-www-form-urlencoded
> 
* upload completely sent off: 14 out of 14 bytes
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Date: Mon, 21 Mar 2016 20:55:00 GMT
< Connection: keep-alive
< Transfer-Encoding: chunked
< 
* Connection #0 to host localhost left intact

您在此行上缺少回车符和换行符:

request_stream << "Content-Type: application/x-www-form-urlencoded";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM