Beast: how to convert http response body to std::string?

Created on 19 Oct 2017  路  10Comments  路  Source: boostorg/beast

`
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 s = res.body.data();    // error here!

i really dont understand the Buffer Types in beast ! orz
help me please

Most helpful comment

You have a few choices here.

First, you can use buffers_to_string like this:

std::cout << boost::beast::buffers_to_string(res.body.data()) << std::endl;

Just a minute correction. It should be

std::cout << boost::beast::buffers_to_string(res.body().data()) << std::endl;

All 10 comments

You can use std::string s = boost::asio::buffer_cast<const char*>(res.body.data());

If the body is of something like multi_buffer, the you need to iterate through the buffer sequence and append it to the string, something like:

for (auto seq : buf_sequence) {
  auto* cbuf = boost::asio::buffer_cast<const char*>(seq);
  s.append(cbuf, boost::asio::buffer_size(seq));
} 

Thank you!
the dynamic_body is multi_buffer , how to decide to use string_body or dynamic_body?

Well, that depends upon what kind of performance characteristics you are looking for. In layman terms, string_body would have all the data in a single heap block. So as and when you get more streamed data, more reallocations (and copy) would happen. multi_buffer is more like a linked list of allocated pools.

You have a few choices here.

First, you can use buffers_to_string like this:

std::cout << boost::beast::buffers_to_string(res.body.data()) << std::endl;

https://github.com/boostorg/beast/blob/885b9dfe0b6bfc7be6a9158d60f0760aa43e748a/include/boost/beast/core/buffers_to_string.hpp#L42

Or you can declare the message to use a string body:

using namespace boost::beast;
http::response<http::string_body> res;

Thanks for your help:)

@vinniefalco I can`t find the file beast/include/boost/beast/core/buffers_to_string.hpp in beast include path.

@lls2wow Which version of Beast?

v84-1

I suggest using version 124, available here:
https://github.com/boostorg/beast/tree/v124

Or, wait until Boost 1.66.0 is released (in a few weeks) and use that.

You have a few choices here.

First, you can use buffers_to_string like this:

std::cout << boost::beast::buffers_to_string(res.body.data()) << std::endl;

Just a minute correction. It should be

std::cout << boost::beast::buffers_to_string(res.body().data()) << std::endl;

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tensor5375 picture tensor5375  路  4Comments

smipi1 picture smipi1  路  7Comments

a1987zz picture a1987zz  路  6Comments

MarcoRhayden picture MarcoRhayden  路  6Comments

jed1 picture jed1  路  4Comments