Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost Beast HTTP

I am working on a http parser, and it looks like boost.beast is a nice one. However, I still have some questions:

*** Assume HTTP Request POST data already received via boost.asio socket. Stored inside a std::string buffer.

  1. Is there any good sample on how to extract http header fields and its value (one-after-another)? I assume it will be an iterator method, but i tried several way and still won't work.

  2. How to extract the http body?

Thank you very much.

like image 657
Jimmy Avatar asked May 23 '18 03:05

Jimmy


People also ask

What is boost beast?

"BOOST BEAST" is a defense puzzle game where players defeat the invading horde of zombies by clearing blocks and summoning animals.

What is Boost ASIO?

Boost. Asio is a cross-platform C++ library for network and low-level I/O programming that provides developers with a consistent asynchronous model using a modern C++ approach. Overview. An overview of the features included in Boost. Asio, plus rationale and design information.


Video Answer


1 Answers

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";
like image 200
sehe Avatar answered Oct 22 '22 11:10

sehe