]> git.tdb.fi Git - libs/net.git/blob - examples/httpget.cpp
70942b7647ffb0bcbdff535e902af0305eadb2ba
[libs/net.git] / examples / httpget.cpp
1 #include <msp/core/application.h>
2 #include <msp/core/getopt.h>
3 #include <msp/http/client.h>
4 #include <msp/http/request.h>
5 #include <msp/http/response.h>
6 #include <msp/io/print.h>
7
8 using namespace std;
9 using namespace Msp;
10
11 class HttpGet: public RegisteredApplication<HttpGet>
12 {
13 private:
14         bool verbose;
15         string url;
16
17 public:
18         HttpGet(int, char **);
19
20         virtual int main();
21 };
22
23 HttpGet::HttpGet(int argc, char **argv):
24         verbose(false)
25 {
26         GetOpt getopt;
27         getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG);
28         getopt(argc, argv);
29
30         const vector<string> &args = getopt.get_args();
31         if(args.empty())
32                 throw usage_error("No URL");
33
34         url = args.front();
35 }
36
37 int HttpGet::main()
38 {
39         Http::Client client;
40
41         if(verbose)
42         {
43                 IO::print("=== Sending request ===\n");
44                 client.start_request(Http::Request::from_url(url));
45                 IO::print(client.get_request()->str());
46                 client.wait_response();
47                 const Http::Response *response = client.get_response();
48                 IO::print("=== Got response ===\n");
49                 IO::print(response->str());
50         }
51         else
52         {
53                 const Http::Response *response = client.get_url(url);
54                 IO::print(response->get_content());
55         }
56
57         return 1;
58 }