|
| 1 | +HTTP client |
| 2 | +=========== |
| 3 | + |
| 4 | +The first code example is the simplest thing you can do with the |
| 5 | +``cpp-netlib``. The application is a simple HTTP client. All we are |
| 6 | +doing is creating and sending an HTTP request to a server and printing |
| 7 | +the response body. Without further ado, the code to do this as |
| 8 | +follows: |
| 9 | + |
| 10 | +:: |
| 11 | + #include <boost/network/protocol/http/client.hpp> |
| 12 | + #include <iostream> |
| 13 | + |
| 14 | + int |
| 15 | + main(int argc, char *argv[]) { |
| 16 | + using namespace boost::network; |
| 17 | + |
| 18 | + if (argc != 2) { |
| 19 | + std::cout << "Usage: " << argv[0] << " [url]" << std::endl; |
| 20 | + return 1; |
| 21 | + } |
| 22 | + |
| 23 | + http::client client; |
| 24 | + http::client::request request(argv[1]); |
| 25 | + request << header("Connection", "close"); |
| 26 | + http::client::response response = client.get(request); |
| 27 | + std::cout << body(response) << std::endl; |
| 28 | + |
| 29 | + return 0; |
| 30 | + } |
| 31 | + |
| 32 | +Since this is the first example, each line will be presented and |
| 33 | +explained in detail. |
| 34 | + |
| 35 | +:: |
| 36 | + #include <boost/network/protocol/http/client.hpp> |
| 37 | + |
| 38 | +All the code needed for the HTTP client resides in this header. |
| 39 | + |
| 40 | +:: |
| 41 | + http::client client; |
| 42 | + |
| 43 | +First we create a ``client`` object. The ``client`` contains all the |
| 44 | +connection and protocol logic. The default HTTP client is version |
| 45 | +1.1, as specified in `RFC 2616`_. |
| 46 | + |
| 47 | +:: |
| 48 | + http::client::request request(argv[1]); |
| 49 | + |
| 50 | +Next, we create a ``request`` object, with a URI string passed as a |
| 51 | +constructor argument. |
| 52 | + |
| 53 | +:: |
| 54 | + request << header("Connection", "close"); |
| 55 | + |
| 56 | +``cpp-netlib`` makes use of stream syntax and *directives* to allow |
| 57 | +developers to build complex message structures with greater |
| 58 | +flexibility and clarity. Here, we add the HTTP header "Connection: |
| 59 | +close" to the request in order to signal that the connection will be |
| 60 | +closed after the request has completed. |
| 61 | + |
| 62 | +:: |
| 63 | + http::client::response response = client.get(request); |
| 64 | + |
| 65 | +Once we've built the request, we then make an HTTP GET request |
| 66 | +throught the ``http::client`` from which an ``http::response`` is |
| 67 | +returned. ``http::client`` supports all common HTTP methods. |
| 68 | + |
| 69 | +:: |
| 70 | + std::cout << body(response) << std::endl; |
| 71 | + |
| 72 | +Finally, though we don't check any error checking, the response body |
| 73 | +is printed to the console using the ``body`` directive. |
| 74 | + |
| 75 | +.. _`RFC 2616`: http://www.w3.org/Protocols/rfc2616/rfc2616.html |
0 commit comments