Я использую Boost :: Beast в моем проекте. Следующий код является модифицированной версией примера кода. Я попытался повторно использовать flat_buffer
и http::response
в следующем коде, но результат неверный. Во втором запросе тело ответа объединяется из двух результатов запроса. Как я могу решить эту проблему?
#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;
}