libtasks Documentation  1.6
jsontest.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 <boost/property_tree/ptree.hpp>
10 #include <boost/property_tree/json_parser.hpp>
11 
12 #include <tasks/dispatcher.h>
13 #include <tasks/net/http_sender.h>
14 
15 using namespace boost::property_tree;
16 using namespace boost::property_tree::json_parser;
17 
19  public:
20  bool handle_response(std::shared_ptr<tasks::net::http_response> response) {
21  std::cout << "Got status " << response->status() << std::endl
22  << "Content Length: " << response->content_length() << std::endl << "Response:" << std::endl
23  << std::endl;
24  if (response->content_length()) {
25  try {
26  ptree pt;
27  read_json(response->content_istream(), pt);
28  print_tree(pt);
29  } catch (std::exception& e) {
30  std::cerr << "error: " << e.what() << std::endl;
31  }
32  } else {
33  std::cout << "empty response" << std::endl;
34  }
35  return false;
36  }
37 
38  void print_tree(ptree& pt, std::string indent = "") {
39  for (auto& v : pt) {
40  std::cout << indent << v.first;
41  if (v.second.empty()) {
42  std::cout << " = " << v.second.data() << std::endl;
43  } else {
44  std::cout << std::endl;
45  print_tree(v.second, indent + " ");
46  }
47  }
48  }
49 };
50 
51 int main(int argc, char** argv) {
52  // initialize the dispatcher first
53  auto disp = tasks::dispatcher::instance();
54  disp->start();
55  auto* sender = new tasks::net::http_sender<json_handler>();
56  // after sending the request we terminate the dispatcher and exit
57  sender->on_finish([] { tasks::dispatcher::instance()->terminate(); });
58  auto request = std::make_shared<tasks::net::http_request>("graph.facebook.com", "/search?q=test");
59  try {
60  sender->send(request);
61  } catch (tasks::tasks_exception& e) {
62  std::cerr << "error: " << e.what() << std::endl;
63  delete sender;
64  disp->terminate();
65  }
66  disp->join();
67  return 0;
68 }
static std::shared_ptr< dispatcher > instance()
Definition: dispatcher.h:75
bool handle_response(std::shared_ptr< tasks::net::http_response > response)
Definition: jsontest.cpp:20
Tasks execption class.
void on_finish(finish_func_worker_t f)
Definition: task.h:56
void print_tree(ptree &pt, std::string indent="")
Definition: jsontest.cpp:38
const char * what() const noexcept
Return the error message.
int main(int argc, char **argv)
Definition: jsontest.cpp:51