C++ library to populate SSL stream with valid HTTP

2019-09-20 19:53发布

问题:

I am using Boost.Asio ssl streams, and got a working encrypted socket from which I can send and receive bytes.

I successfully did a GET request with the following code :

// Construct HTTP request (using vanilla std::ostream)
std::ostream request_stream(&request);
request_stream << "GET  / HTTP/1.0\r\n";
request_stream << "Host: " << argv[1] << "\r\n";
...
// Send request
ssl::stream<tcp::socket> socket
boost::asio::write(socket, request);

And I would now love to find a small C++ library that would provide an easy way to get the ostream loaded with a valid HTTP request !

回答1:

Since you're already using Boost.Asio, consider using Boost.Beast which is a low-level HTTP library. Example of sending a GET request using Boost.Beast:

using namespace boost::beast;

// Set up an HTTP GET request message
http::request<http::empty_body> req{http::verb::get, "/", 11};
req.set(http::field::host, "www.example.com");
req.set(http::field::user_agent, "Beast/1.0);

// Send the HTTP request to the remote host
http::write(socket, req);

The full example is here: https://github.com/boostorg/beast/blob/master/example/http/client/sync/http_client_sync.cpp

Beast is available in Boost versions 1.66 and later. Here is the documentation page, which includes many examples: http://www.boost.org/doc/libs/1_66_0/libs/beast/doc/html/index.html

If you really want to write the HTTP request to a std::ostream, Beast supports operator<< for HTTP messages (it is mainly there for debugging), but I think you are better off just writing it directly to the ip::tcp::socket or ssl::stream using Beast.