]> 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.add_argument("url", url, GetOpt::REQUIRED_ARG);
32         getopt(argc, argv);
33 }
34
35 int HttpGet::main()
36 {
37         Http::Client client;
38         client.signal_socket_error.connect(sigc::mem_fun(this, &HttpGet::socket_error));
39
40         if(verbose)
41         {
42                 IO::print("=== Sending request ===\n");
43                 client.start_request(Http::Request::from_url(url));
44                 IO::print(client.get_request()->str());
45                 client.wait_response();
46                 const Http::Response *response = client.get_response();
47                 if(response)
48                 {
49                         IO::print("=== Got response ===\n");
50                         IO::print(response->str());
51                 }
52         }
53         else
54         {
55                 const Http::Response *response = client.get_url(url);
56                 if(response)
57                         IO::print(response->get_content());
58         }
59
60         return 1;
61 }
62
63 void HttpGet::socket_error(const exception &e)
64 {
65         IO::print("=== Error ===\n");
66         IO::print("%s\n", Debug::demangle(typeid(e).name()));
67         IO::print("%s\n", e.what());
68 }