首页 > 解决方案 > 如何从 Boost 中的 http::response 读取标头

问题描述

尝试使用 boost 进行 http 连接。到目前为止,我一直遵循官方指南,并且能够正确获得响应并解析正文:

 // 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()) };

现在的问题是我不知道如何获取标题并检查状态码。有什么帮助吗?

标签: boostandroid-ndkboost-asio

解决方案


状态码不是标头,它只是响应对象的一个​​属性:

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

推荐阅读