Starting from a simple example: https://www.boost.org/doc/libs/develop/libs/beast/example/http/client/sync/http_client_sync.cpp
// Declare a container to hold the response
http::response<http::dynamic_body> res;
// Receive the HTTP response
http::read(socket, buffer, res);
Extract The Headers
The response object already contains all the goods:
for(auto const& field : res)
std::cout << field.name() << " = " << field.value() << "\n";
std::cout << "Server: " << res[http::field::server] << "\n";
You can also just stream the entire response object:
std::cout << res << std::endl;
Extract The Body
std::cout << "Body size is " << res.body().size() << "\n";
To actually use the "dynamic_body", use standard Asio buffer manipulation:
#include <boost/asio/buffers_iterator.hpp>
#include <boost/asio/buffers_iterator.hpp>
std::string body { boost::asio::buffers_begin(res.body().data()),
boost::asio::buffers_end(res.body().data()) };
std::cout << "Body: " << std::quoted(body) << "\n";
Alternatively, see beast::buffers_to_string
Obviously, things become more straight-forward when using a string_body
:
std::cout << "Body: " << std::quoted(res.body()) << "\n";
std::quoted
! An alternative for output isstd::ostream&
usingstd::cout << beast::buffers(res.body().data()) << "\n";
. The functionbeast::buffers
adapts a buffer sequence into something that works withoperator<<
. – Darvon