Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple interface for getting HTML content in Boost.Asio

There are a lot of examples how to make HTTP request to a server and get reply via boost.asio library. However, I couldn't find a good example of simple interface and wondering, if I need to implement it myself.

For instance, if I need to get content of http://www.foo.bar/path/to/default.html, is there any way to get a content without validating URL, making HTTP request and parsing server answer?

Basically, I am looking for something like this:

std::string str = boost::asio::get_content("http://www.foo.bar/path/to/default.html");
std::cout << str;

#
<HTML>
  <BODY>
    Simple HTML page!
  </BODY>
</HTML>

There are couple of things that I would like to avoid using boost.asio.

  • Avoid parsing and validating URL.
  • Manually creating HTTP request.
  • Cutting HTTP response from HTML page content.
like image 381
user44986 Avatar asked Nov 30 '22 19:11

user44986


1 Answers

Since then, there is a newcomer; the C++ Network Library: cpp-netlib as pointed out here.

You wanted to use asio. I suppose you fancied the portability and the ease of use of this lib, so cpp-netlib will be a great choice in that case. It is based on same principles as boost and its authors aim at integrating it into boost.

It is pretty simple to use:

http::client client;
/*<< Creates a request using a URI supplied on the command line. >>*/
http::client::request request("http://www.foo.bar/path/to/default.html");
/*<< Gets a response from the HTTP server. >>*/
http::client::response response = client.get(request);
/*<< Prints the response body to the console. >>*/
std::cout << body(response) << std::endl;

I haven't tried this one but it seems to be possible to do exactly what you need:

cout << body(client().get(client::request("http://www.foo.bar/path/to/default.html")));

This question was asked a long time ago, sorry for digging it out of its grave.

like image 86
Coyote Avatar answered Dec 04 '22 23:12

Coyote