BOOST 请求发送 JSON 数据

BOOST request sending JSON data

我想将 json 数据传输到 cpp 中 json boost 的请求中。

如果我在 boost

中服用 json

int outer=2;

value data = {
        {"dia",outer},
        {"sleep_time_in_s",0.1}
    };

request.body()=data;

像上面一样,我想从boost客户端向服务器发送数据,但它是通过错误 有没有人理解下面的错误建议我。

error C2679: binary '=': no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)

C:\Boost\boost/beast/core/multi_buffer.hpp(360,25): message : could be 'boost::beast::basic_multi_buffer<std::allocator<char>> &boost::beast::basic_multi_buffer<std::allocator<char>>::operator =(const boost::beast::basic_multi_buffer<std::allocator<char>> &)'

2>C:\Boost\boost/beast/core/multi_buffer.hpp(345,5): message : or       'boost::beast::basic_multi_buffer<std::allocator<char>> &boost::beast::basic_multi_buffer<std::allocator<char>>::operator =(boost::beast::basic_multi_buffer<std::allocator<char>> &&)'

2>C:\Development\qa-cal\sysqa_cpp\src\guiClient\boostHttpClient.cpp(90,31): message : while trying to match the argument list '(boost::beast::basic_multi_buffer<std::allocator<char>>, std::string)'

C++ 是强类型的。您不能将 json::value 分配给其他内容。在这种情况下,您的 body() 可能类似于 std::string.

假设 valueboost::json::value 你应该这样写:

request.body() = serialize(data);

其中 boost::json::serializedata 值序列化为字符串表示形式。

Live Demo

#include <boost/beast.hpp>
#include <boost/json.hpp>
#include <boost/json/src.hpp>
#include <iostream>
namespace http = boost::beast::http;

int main() {
    using boost::json::value;
    http::request<http::string_body> request(
            http::verb::post, "/some/api", 11);

    {
        int outer = 2;
        value data  = {
            {"dia", outer},
            {"sleep_time_in_s", 0.1},
        };
        request.body() = serialize(data);
    }

    request.prepare_payload();

    std::cout << request;
}

版画

POST /some/api HTTP/1.1
Content-Length: 32
{"dia":2,"sleep_time_in_s":1E-1}