json BOOST ASIO POST HTTP请求--头和正文

uhry853o  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(68)

我一直在努力让这个工作了几天,但我一直得到一个400错误从服务器。
基本上,我尝试做的是向服务器发送一个httpPOST请求,该请求需要一个带有几个属性的JSON请求体。
这些是我目前使用的库
更新-2013年7月23日上午10:00注意到我正在使用TCP而不是HTTP,不确定这会对HTTP调用产生多大影响,但我找不到客户端使用纯HTTP与BOOST::ASIO的任何示例

#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <boost/asio.hpp>

#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

using boost::property_tree::ptree; using boost::property_tree::read_json; using boost::property_tree::write_json;

using boost::asio::ip::tcp;

字符串
设置代码

// Get a list of endpoints corresponding to the server name.
tcp::resolver resolver(io_service);
tcp::resolver::query query(part1, "http");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

// Try each endpoint until we successfully establish a connection.
tcp::socket socket(io_service);
boost::asio::connect(socket, endpoint_iterator);

// Form the request. We specify the "Connection: close" header so that the
// server will close the socket after transmitting the response. This will
// allow us to treat all data up until the EOF as the content.
boost::asio::streambuf request;
std::ostream request_stream(&request);


JSON正文

ptree root, info;
root.put ("some value", "8");
root.put ( "message", "value value: value!");
info.put("placeholder", "value");
info.put("value", "daf!");
info.put("module", "value");
root.put_child("exception", info);

std::ostringstream buf; 
write_json (buf, root, false);
std::string json = buf.str();


标题和连接请求

request_stream << "POST /title/ HTTP/1.1 \r\n";
request_stream << "Host:" << some_host << "\r\n";
request_stream << "User-Agent: C/1.0";
request_stream << "Content-Type: application/json; charset=utf-8 \r\n";
request_stream << json << "\r\n";
request_stream << "Accept: */*\r\n";    
request_stream << "Connection: close\r\n\r\n";

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


我把位置保持器值,但如果你看到任何不工作,在我的代码跳出来,请让我知道我不知道为什么我一直得到一个400,坏的请求。
关于钻机的信息
C++
Win7
Visual Studio

wyyhbhjk

wyyhbhjk1#

虽然这个问题很老了,我想为那些面临类似http POST问题的用户发布这个答案。
服务器向你发送HTTP 400意味着“BAD REQUEST”。这是因为你形成请求的方式有点错误。
下面是发送包含JSON数据的POST请求的正确方法。

#include <string>  //for length()

request_stream << "POST /title/ HTTP/1.1 \r\n";
request_stream << "Host:" << some_host << "\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: " << json.length() << "\r\n";    
request_stream << "Connection: close\r\n\r\n";  //NOTE THE Double line feed
request_stream << json;

字符串
当你在POST请求中发送任何数据(json,string等)时,请确保:

**(1)*Content-Length:**准确。
**(2)**您将数据放在请求的末尾,并留出行间距。
**(3)**为了实现这一点(第二点),你必须在你的header请求的最后一个header中提供双行提要(即\r\n\r\n)。这告诉header HTTP请求内容已经结束,现在它(服务器)将获取数据。

如果你不这样做,那么服务器就无法理解header在哪里结束?以及data在哪里开始?所以,它会一直等待承诺的数据(它挂起)。
免责声明:如果有不准确之处,请随时编辑。

相关问题