如何在 Boost 中从 http::response 读取 header

How to read header from http::response in Boost

正在尝试使用 boost 进行 http 连接。 到目前为止,我已经按照官方指南进行操作,并且能够正确获得响应并解析 body:

 // Send the HTTP request to the remote host
http::write(stream, req);

// This buffer is used for reading and must be persisted
beast::flat_buffer buffer;

// Declare a container to hold the response
http::response<http::dynamic_body> res;

// Receive the HTTP response
http::read(stream, buffer, res);

// Write the message to standard out
std::cout << res << std::endl;

std::string body { boost::asio::buffers_begin(res.body().data()),
                   boost::asio::buffers_end(res.body().data()) };

现在的问题是不知道如何获取header和查看状态码。有帮助吗?

状态代码不是 header,它只是响应 object:

的 属性
std::cout << res.result_int() << std::endl;
std::cout << res.result() << std::endl;
std::cout << res.reason() << std::endl;

for (auto& h : res.base()) {
    std::cout << "Field: " << h.name() << "/text: " << h.name_string() << ", Value: " << h.value() << "\n";
}

打印类似

的内容
200
OK
OK
Field: Age/text: Age, Value: 437767
Field: Cache-Control/text: Cache-Control, Value: max-age=604800
Field: Content-Type/text: Content-Type, Value: text/html; charset=UTF-8
Field: Date/text: Date, Value: Tue, 23 Jun 2020 16:43:43 GMT
Field: ETag/text: Etag, Value: "3147526947+ident"
Field: Expires/text: Expires, Value: Tue, 30 Jun 2020 16:43:43 GMT
Field: Last-Modified/text: Last-Modified, Value: Thu, 17 Oct 2019 07:18:26 GMT
Field: Server/text: Server, Value: ECS (bsa/EB15)
Field: Vary/text: Vary, Value: Accept-Encoding
Field: <unknown-field>/text: X-Cache, Value: HIT
Field: Content-Length/text: Content-Length, Value: 1256