8

我一直试图让它工作几天,但是我一直从服务器收到 400 错误。

基本上,我要做的是将http POST 请求发送到需要具有几个属性的JSON 请求主体的服务器。

这些是我目前正在使用的库

更新 --- 7/23/13 上午 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

视觉工作室

4

1 回答 1

16

虽然这个问题已经很老了,但我想为面临类似 http POST 问题的用户发布这个答案。

服务器向您发送 HTTP 400 表示“错误请求”。这是因为您形成请求的方式有点错误。

以下是发送包含 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、字符串等)时,请确保:

(1) Content-Length:准确。

(2)您将数据放在请求的末尾并带有行间距。

(3)并且为了实现这一点(第 2 点),您必须在标头请求的最后一个标头中提供双换行符(即 \r\n\r\n)。这告诉标头 HTTP 请求内容已经结束,现在它(服务器)将获取数据。

如果您不这样做,那么服务器无法理解标头在哪里结束?数据从哪里开始?所以,它一直在等待承诺的数据(它挂起)。

免责声明:如有不准确之处,请随时编辑。

于 2015-04-10T14:46:02.127 回答