C++ library to populate SSL stream with valid HTTP requests
Asked Answered
A

1

-1

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 !

Alright answered 18/3, 2018 at 22:47 Comment(0)
C
2

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.

Charry answered 18/3, 2018 at 22:57 Comment(3)
That seems just great, I'll check it out & accept your answer when I'll get it working. Thumbs up !Alright
Working fine ! How come i am able to write with the boost::beast::http write method to a boost::asio::ssl::stream ? Common parent class ?Alright
@AlexandreRozier Because ssl::stream and tcp::ip::socket both meet the requirements of SyncStream and AsyncStream. Beast's stream algorithms are templated, and work with any type that meets those requirements. They are documented here (click the links on the page) boost.org/doc/libs/1_66_0/libs/beast/doc/html/beast/concepts/…Charry

© 2022 - 2024 — McMap. All rights reserved.