一般来说,不要对specific implementation编程,而是对concept编程.这里,dynamic_body
documents:
该正文使用DynamicBuffer
作为基于内存的容器,用于保存消息有效负载.可以对使用此正文类型的消息进行序列化和解析.
您不需要这个概念,因为无论如何您都将完全在内存中使用它,但是如果您需要的话,您应该这样做:
net::streambuf sb;
sb.commit(net::buffer_copy(sb.prepare(body.size()), body.cdata()));
std::istream is(&sb);
ptree doc;
read_json(is, doc);
看它100
#include <boost/asio.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <boost/beast/http.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
namespace net = boost::beast::net;
namespace http = boost::beast::http;
using boost::property_tree::ptree;
int main() {
net::posix::stream_descriptor input(net::system_executor{}, 0); // stdin
http::response<http::dynamic_body> res;
{
net::streambuf readbuf;
http::read(input, readbuf, res);
}
auto& body = res.body();
net::streambuf sb;
sb.commit(net::buffer_copy(sb.prepare(body.size()), body.cdata()));
std::istream is(&sb);
ptree doc;
read_json(is, doc);
write_json(std::cout << "Parsed body: ", doc);
}
它从stdin读取一个示例响应,让我们使用
HTTP/1.1 200 OK
Content-Length: 50
{"this":{"is":[1,2,3], "a":"sample"}, "object":42}
如下所示:
g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp && ./a.out <<< $'HTTP/1.1 200 OK\r\nContent-Length: 50\r\n\r\n{\"this\":{\"is\":[1,2,3], \"a\":\"sample\"}, \"object\":42}'
版画
Parsed body: {
"this": {
"is": [
"1",
"2",
"3"
],
"a": "sample"
},
"object": "42"
}
然而,
现在我们已经回答了问题,让我们添加上下文:
相反,您可以使用最简单的模型,并使用JSON库,例如,Boost.JSON:
100
#include <boost/asio.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <boost/beast/http.hpp>
#include <boost/json/src.hpp> // for header-only
#include <iostream>
namespace net = boost::beast::net;
namespace http = boost::beast::http;
namespace json = boost::json;
int main() {
net::posix::stream_descriptor input(net::system_executor{}, 0); // stdin
http::response<http::string_body> res;
{
net::streambuf readbuf;
http::read(input, readbuf, res);
}
auto doc = json::parse(res.body());
std::cout << "Parsed body: " << doc << "\n";
}
它的代码更少,效率更高,最重要的是,正确处理JSON!