libtasks Documentation  1.6
http_client.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2013-2014 ADTECH GmbH
3  * Licensed under MIT (https://github.com/adtechlabs/libtasks/blob/master/COPYING)
4  *
5  * Author: Andreas Pohl
6  */
7 
8 #include <iostream>
9 #include <memory>
10 
11 #include <tasks/dispatcher.h>
12 #include <tasks/net/http_sender.h>
13 
15  public:
16  bool handle_response(std::shared_ptr<tasks::net::http_response> response) {
17  std::cout << "Got status " << response->status() << std::endl;
18  if (response->content_length()) {
19  std::cout << "Content:" << std::endl << response->content_p() << std::endl;
20  }
21  return false;
22  }
23 };
24 
25 int main(int argc, char** argv) {
26  // initialize the dispatcher first
27  auto disp = tasks::dispatcher::instance();
28  disp->start();
29  auto* sender = new tasks::net::http_sender<test_handler>();
30  // after sending the request we terminate the dispatcher and exit
31  sender->on_finish([disp] { disp->terminate(); });
32  auto request = std::make_shared<tasks::net::http_request>("www.google.com", "/");
33  std::cout << "sending" << std::endl;
34  try {
35  sender->send(request);
36  } catch (tasks::tasks_exception& e) {
37  std::cerr << "error: " << e.what() << std::endl;
38  delete sender;
39  // shutdown the dispatcher
40  disp->terminate();
41  }
42  disp->join();
43  return 0;
44 }
static std::shared_ptr< dispatcher > instance()
Definition: dispatcher.h:75
Tasks execption class.
bool handle_response(std::shared_ptr< tasks::net::http_response > response)
Definition: http_client.cpp:16
void on_finish(finish_func_worker_t f)
Definition: task.h:56
const char * what() const noexcept
Return the error message.
int main(int argc, char **argv)
Definition: http_client.cpp:25