Search code examples
c++boost-asioboost-beast

How to reuse http::beast::flat_buffer and http::response?


I'm using boost::beast in my project. Following code is a modified version of example code. I tried to reuse flat_buffer and http::response in the following code, but the result is wrong. In the second query, the response body is concatenate of two query result. How can I solve this problem?

#include <iostream>
#include <string>

#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>

int main(int argc, char** argv) {
  using tcp = boost::asio::ip::tcp;       // from <boost/asio/ip/tcp.hpp>
  namespace http = boost::beast::http;    // from <boost/beast/http.hpp>
  auto const host = "www.example.com";
  auto const port = "80";
  auto const target = "/";
  int version = 11;

  boost::asio::io_context ioc;
  tcp::resolver resolver{ioc};
  tcp::socket socket{ioc};

  auto const results = resolver.resolve(host, port);

  // Make the connection on the IP address we get from a lookup
  boost::asio::connect(socket, results.begin(), results.end());

  // Set up an HTTP GET request message
  http::request<http::string_body> req{http::verb::get, target, version};
  req.set(http::field::host, host);
  req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);

  // This buffer is used for reading and must be persisted
  boost::beast::flat_buffer buffer;
  // Declare a container to hold the response
  http::response<http::dynamic_body> res;

  for (int n = 0; n < 2; n++) {
    http::write(socket, req);
    http::read(socket, buffer, res);
    // Write the message to standard out
    std::cout << res << std::endl;
    std::cout << "+++++++++++++++++\n";
  }

  // Gracefully close the socket
  boost::system::error_code ec;
  socket.shutdown(tcp::socket::shutdown_both, ec);
  return EXIT_SUCCESS;
}

Solution

  • The http::read is additive. If you want the buffer empty before the call to read you will need to do it manually.

    One way is like this:

    buffer.consume(buffer.size());

    The beast team are always happy to help on slack if you have access to it:

    http://slack.cpp.al

    channel #beast