|
|
@ -0,0 +1,73 @@ |
|
|
|
#include "webclient.hh"
|
|
|
|
|
|
|
|
#include <string>
|
|
|
|
#include <stdexcept>
|
|
|
|
#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>
|
|
|
|
|
|
|
|
namespace pEp |
|
|
|
{ |
|
|
|
|
|
|
|
namespace beast = boost::beast; // from <boost/beast.hpp>
|
|
|
|
namespace http = beast::http; // from <boost/beast/http.hpp>
|
|
|
|
namespace net = boost::asio; // from <boost/asio.hpp>
|
|
|
|
using tcp = net::ip::tcp; // from <boost/asio/ip/tcp.hpp>
|
|
|
|
|
|
|
|
|
|
|
|
HttpError::HttpError(unsigned error_code, const std::string& error_message) |
|
|
|
: runtime_error("HTTP Error: " + std::to_string(error_code) + " " + error_message) |
|
|
|
{} |
|
|
|
|
|
|
|
|
|
|
|
// based on https://www.boost.org/doc/libs/1_75_0/libs/beast/doc/html/beast/quick_start/http_client.html
|
|
|
|
std::string Webclient::get(const std::string& url) |
|
|
|
{ |
|
|
|
// The io_context is required for all I/O
|
|
|
|
net::io_context ioc; |
|
|
|
|
|
|
|
// These objects perform our I/O
|
|
|
|
tcp::resolver resolver(ioc); |
|
|
|
beast::tcp_stream stream(ioc); |
|
|
|
|
|
|
|
// Look up the domain name
|
|
|
|
auto const results = resolver.resolve(m_server_name, std::to_string(m_port)); |
|
|
|
|
|
|
|
// Make the connection on the IP address we get from a lookup
|
|
|
|
stream.connect(results); |
|
|
|
|
|
|
|
// Set up an HTTP GET request message
|
|
|
|
http::request<http::string_body> req{http::verb::get, url, 11}; |
|
|
|
req.set(http::field::host, m_server_name); |
|
|
|
req.set(http::field::user_agent, "pEp::Webclient 0.1"); |
|
|
|
|
|
|
|
// Send the HTTP request to the remote host
|
|
|
|
http::write(stream, req); |
|
|
|
|
|
|
|
// This buffer is used for reading and must be persisted
|
|
|
|
beast::flat_buffer buffer; |
|
|
|
|
|
|
|
// Declare a container to hold the response
|
|
|
|
http::response<http::dynamic_body> res; |
|
|
|
|
|
|
|
// Receive the HTTP response
|
|
|
|
http::read(stream, buffer, res); |
|
|
|
|
|
|
|
// Gracefully close the socket
|
|
|
|
beast::error_code ec; |
|
|
|
stream.socket().shutdown(tcp::socket::shutdown_both, ec); |
|
|
|
|
|
|
|
// not_connected happens sometimes
|
|
|
|
// so don't bother reporting it.
|
|
|
|
//
|
|
|
|
if(ec && ec != beast::errc::not_connected) |
|
|
|
throw beast::system_error{ec}; |
|
|
|
|
|
|
|
// If we get here then the connection is closed gracefully
|
|
|
|
return boost::beast::buffers_to_string(res.body().data()); |
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
} // end of namespace pEp
|