Created
July 24, 2023 06:39
-
-
Save M0nteCarl0/2f75f08cf54b4df99b534ccec80f0110 to your computer and use it in GitHub Desktop.
Boost,beast HTTP client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <boost/asio.hpp> | |
#include <boost/beast.hpp> | |
namespace asio = boost::asio; | |
namespace beast = boost::beast; | |
using tcp = asio::ip::tcp; | |
int main() | |
{ | |
try | |
{ | |
// Create an asio::io_context | |
asio::io_context io_context; | |
// Create a resolver and query the server endpoint | |
tcp::resolver resolver(io_context); | |
auto const results = resolver.resolve("example.com", "http"); | |
// Create a TCP socket and establish a connection | |
tcp::socket socket(io_context); | |
asio::connect(socket, results.begin(), results.end()); | |
// Create an HTTP request | |
beast::http::request<beast::http::string_body> request(beast::http::verb::get, "/", 11); | |
request.set(beast::http::field::host, "example.com"); | |
request.set(beast::http::field::user_agent, "Boost Beast HTTP Client"); | |
// Send the HTTP request | |
beast::http::write(socket, request); | |
// Receive the HTTP response | |
beast::flat_buffer buffer; | |
beast::http::response<beast::http::dynamic_body> response; | |
beast::http::read(socket, buffer, response); | |
// Print the response body | |
std::cout << beast::buffers_to_string(response.body().data()) << std::endl; | |
} | |
catch (const std::exception& ex) | |
{ | |
std::cerr << "Error: " << ex.what() << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment