]> git.tdb.fi Git - libs/net.git/blobdiff - examples/httpget.cpp
Add example of Http::Client usage
[libs/net.git] / examples / httpget.cpp
diff --git a/examples/httpget.cpp b/examples/httpget.cpp
new file mode 100644 (file)
index 0000000..70942b7
--- /dev/null
@@ -0,0 +1,58 @@
+#include <msp/core/application.h>
+#include <msp/core/getopt.h>
+#include <msp/http/client.h>
+#include <msp/http/request.h>
+#include <msp/http/response.h>
+#include <msp/io/print.h>
+
+using namespace std;
+using namespace Msp;
+
+class HttpGet: public RegisteredApplication<HttpGet>
+{
+private:
+       bool verbose;
+       string url;
+
+public:
+       HttpGet(int, char **);
+
+       virtual int main();
+};
+
+HttpGet::HttpGet(int argc, char **argv):
+       verbose(false)
+{
+       GetOpt getopt;
+       getopt.add_option('v', "verbose", verbose, GetOpt::NO_ARG);
+       getopt(argc, argv);
+
+       const vector<string> &args = getopt.get_args();
+       if(args.empty())
+               throw usage_error("No URL");
+
+       url = args.front();
+}
+
+int HttpGet::main()
+{
+       Http::Client client;
+
+       if(verbose)
+       {
+               IO::print("=== Sending request ===\n");
+               client.start_request(Http::Request::from_url(url));
+               IO::print(client.get_request()->str());
+               client.wait_response();
+               const Http::Response *response = client.get_response();
+               IO::print("=== Got response ===\n");
+               IO::print(response->str());
+       }
+       else
+       {
+               const Http::Response *response = client.get_url(url);
+               IO::print(response->get_content());
+       }
+
+       return 1;
+}