简体   繁体   中英

Empty body in Boost::ASIO HTTP POST

I tried using Post method with the below code. On the server side the body is always empty.

tcp::endpoint ip_port(address::from_string(host), port);
socket.connect(ip_port);

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

request_stream << "POST /myservice HTTP/1.1\n\n";
request_stream << "Host:" << "host:port" << "\r\n";
request_stream << "User-Agent: C/1.0" << "\r\n";
request_stream << "Content-Type: application/json; charset=utf-8\r\n";
request_stream << "Accept: */*\r\n";
request_stream << "Content-Length: ";
request_stream << json.length() + "\r\n";
request_stream << "Connection: close\r\n\r\n"; 
request_stream << json;

boost::asio::write(socket, request);

I checked on server side by sending request from other rest client, it works fine. Please let me know what I am doing wrong.

Finally, I found it. The problem with \\n\\n in the first line. If there are two \\n, request ends there. I tried the below code and I'm able to get the json body on server side.

requestStream << "POST " << "/myservice" << " HTTP/1.1\r\n";
requestStream << "Host: " << "myhost" << "\r\n";
requestStream << "Accept: application/json\r\n";
requestStream << "Content-Type: application/json; charset=UTF-8\r\n";
requestStream << "Content-Length: " << json.length() << "\r\n";
requestStream << "\r\n";
requestStream << json << "\n\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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