Search code examples
boostboost-beast

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


Reference: 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

Question> I would like to know how to convert res_::base() to std::string. In other words, I need to find a way to convert http::basic_fields to std::string if my understanding is correct.

Thank you


Solution

  • You can stream it, or let lexical_cast do that for you:

    #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;
        }
    }
    

    Prints the same both ways:

    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