如何将 http::response<http::string_body>::base() 转换为 std::string?

How to convert http::response<http::string_body>::base() to std::string?

参考: base basic_fields

base() : Returns the header portion of the message.
    
http::response<http::string_body> res_;
std::cout << "Type of res_.base() : " << typeid(res_.base()).name() << std::endl;
// Type of res_.base() : N5boost5beast4http6headerILb0ENS1_12basic_fieldsISaIcEEEEE

问题> 我想知道如何将 res_::base() 转换为 std::string。 换句话说,如果我的理解是正确的,我需要找到一种将http::basic_fields转换为std::string的方法。

谢谢

res 有 begin() 和 end(),因此您可以迭代 res 并使用 name() 和 value() 打印字段

http::response<http::string_body> res;
// some code
for (auto const &header : res)
  {
    std::cout << "name: " << header.name () << " value: " << header.value () << std::endl;
  }

示例输出:

name: Server value: nginx
name: Date value: Thu, 17 Mar 2022 15:57:46 GMT
name: Content-Type value: application/json
name: Transfer-Encoding value: chunked
name: Connection value: keep-alive
name: Access-Control-Allow-Origin value: null
name: Access-Control-Allow-Credentials value: true
name: Access-Control-Allow-Headers value: Origin, Content-Type, Accept, Authorization, X-Requested-With
name: Access-Control-Allow-Methods value: POST, GET, PUT, DELETE, OPTIONS
name: Strict-Transport-Security value: max-age=63072000; includeSubdomains; preload
name: <unknown-field> value: strict-origin

您可以流式传输,或让 lexical_cast 为您完成:

#include <boost/beast.hpp>
#include <boost/lexical_cast.hpp>
#include <iostream>
namespace net = boost::asio;
namespace beast = boost::beast;
namespace http = beast::http;
using net::ip::tcp;

int main() {
    net::io_context io;
    tcp::socket conn(io);
    connect(conn, tcp::resolver{io}.resolve("httpbin.org", "http"));

    {
        http::request<http::empty_body> req{http::verb::get, "/get", 11};
        req.set(http::field::host, "httpbin.org");
        http::write(conn, req);
    }

    {
        http::response<http::string_body> resp;
        beast::flat_buffer buf;
        http::read(conn, buf, resp);

        std::string const strHeaders =
            boost::lexical_cast<std::string>(resp.base());

        std::cout << "Directly:   " << resp.base() << std::endl;
        std::cout << "strHeaders: " << strHeaders  << std::endl;
    }
}

两种方式打印相同:

Directly:   HTTP/1.1 200 OK
Date: Thu, 17 Mar 2022 22:19:17 GMT
Content-Type: application/json
Content-Length: 199
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true


strHeaders: HTTP/1.1 200 OK
Date: Thu, 17 Mar 2022 22:19:17 GMT
Content-Type: application/json
Content-Length: 199
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true