]> git.tdb.fi Git - libs/net.git/blob - examples/httpget.cpp
Add a dynamic receiver class for more flexible packet handling
[libs/net.git] / examples / httpget.cpp
1 #include <msp/core/application.h>
2 #include <msp/core/getopt.h>
3 #include <msp/debug/demangle.h>
4 #include <msp/http/client.h>
5 #include <msp/http/request.h>
6 #include <msp/http/response.h>
7 #include <msp/io/print.h>
8
9 using namespace std;
10 using namespace Msp;
11
12 class HttpGet: public RegisteredApplication<HttpGet>
13 {
14 private:
15         bool verbose;
16         string url;
17
18 public:
19         HttpGet(int, char **);
20
21         virtual int main();
22 private:
23         void socket_error(const exception &);
24 };
25
26 HttpGet::HttpGet(int argc, char **argv):
27         verbose(false)
28 {
29         GetOpt getopt;
30         getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG);
31         getopt(argc, argv);
32
33         const vector<string> &args = getopt.get_args();
34         if(args.empty())
35                 throw usage_error("No URL");
36
37         url = args.front();
38 }
39
40 int HttpGet::main()
41 {
42         Http::Client client;
43         client.signal_socket_error.connect(sigc::mem_fun(this, &HttpGet::socket_error));
44
45         if(verbose)
46         {
47                 IO::print("=== Sending request ===\n");
48                 client.start_request(Http::Request::from_url(url));
49                 IO::print(client.get_request()->str());
50                 client.wait_response();
51                 const Http::Response *response = client.get_response();
52                 if(response)
53                 {
54                         IO::print("=== Got response ===\n");
55                         IO::print(response->str());
56                 }
57         }
58         else
59         {
60                 const Http::Response *response = client.get_url(url);
61                 if(response)
62                         IO::print(response->get_content());
63         }
64
65         return 1;
66 }
67
68 void HttpGet::socket_error(const exception &e)
69 {
70         IO::print("=== Error ===\n");
71         IO::print("%s\n", Debug::demangle(typeid(e).name()));
72         IO::print("%s\n", e.what());
73 }