Menu

[r224]: / trunk / libs / network / example / http_client.cpp  Maximize  Restore  History

Download this file

86 lines (71 with data), 2.5 kB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Copyright Dean Michael Berris 2008.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//[ http_client_main
/*`
This application takes a URL as a command line argument and prints
the resource to the console.
*/
#include <boost/program_options.hpp>
#include <boost/network/protocol/http.hpp>
#include <string>
#include <iostream>
namespace po = boost::program_options;
using namespace std;
int main(int argc, char * argv[]) {
po::options_description options("Allowed options");
string output_filename, source;
bool show_headers;
options.add_options()
("help,h", "produce help message")
("headers,H", "print headers")
("source,s", po::value<string>(&source), "source URL")
;
po::positional_options_description positional_options;
positional_options.add("source", 1);
po::variables_map vm;
try {
po::store(po::command_line_parser(argc, argv).options(options).positional(positional_options).run(),
vm);
po::notify(vm);
} catch(exception & e) {
cout << "Error: " << e.what() << endl;
cout << options << endl;
return EXIT_FAILURE;
};
if (vm.count("help")) {
cout << options << endl;
return EXIT_SUCCESS;
};
if (vm.count("source") < 1) {
cout << "Error: Source URL required." << endl;
cout << options << endl;
return EXIT_FAILURE;
};
show_headers = vm.count("headers") ? true : false ;
try {
using namespace boost::network;
http::request request(source);
http::client client;
http::response response;
response = client.get(request);
if (show_headers) {
headers_range<http::response>::type headers_ = headers(response);
boost::range_iterator<headers_range<http::response>::type>::type header, past_end;
header = begin(headers_);
past_end = end(headers_);
while (header != past_end) {
cout << header->first << ": " << header->second << endl;
++header;
};
cout << endl;
};
cout << body(response) << endl;
} catch (exception & e) {
cout << "Error: " << e.what() << endl;
return EXIT_FAILURE;
};
return EXIT_SUCCESS;
}
//]