1 #define CPPHTTPLIB_OPENSSL_SUPPORT
2 #include "httplib/httplib.h"
12 std::string protocol = url.substr(0,url.find(
"://"));
13 if ( protocol ==
"http" ) {
15 }
else if ( protocol ==
"https" ) {
18 throw Exception(
"Protocol " + protocol +
" not implemented in Client.");
21 std::string rest = url.substr(protocol.length() + 3),
22 addr = rest.substr(0, rest.find(
"/")),
23 path = rest.substr(addr.length());
29 return std::make_pair(addr,path);
34 std::thread t(&Client::_get_thread,
this,url,handler);
42 for(
auto response : _responses ) {
43 std::get<1>(response)(std::get<0>(response));
54 const std::shared_ptr<httplib::Response> Client::_get_aux(std::string url) {
57 httplib::SSLClient cli(parts.first.c_str(), 443);
58 return cli.Get(parts.second.c_str());
60 httplib::Client cli(parts.first.c_str(), 80);
61 return cli.Get(parts.second.c_str());
65 void Client::_get_thread(std::string url, std::function<
void(json&)> handler) {
71 auto response = _get_aux(url);
73 if (response && response->status == 200) {
74 json_response = json::parse(response->body);
75 }
else if ( response ) {
76 std::cout <<
"Warning:: Elma client connected to a server that returned Error: "
80 std::cout <<
"Warning:: Elma client returned no result"
84 }
catch (
const httplib::Exception& e) {
85 std::cout <<
"Warning: Elma client failed: "
88 }
catch(
const json::exception& e ) {
89 std::cout <<
"Warning: Elma client could not parse response: "
93 std::cout <<
"Warning: Elma client failed with no message\n";
97 _responses.push_back(std::make_tuple(json_response, handler));
std::pair< std::string, std::string > url_parts(std::string url)
An HTTP client for connecting to json services.
An exception class for Elma.
Client & get(std::string url, std::function< void(json &)> handler)
Client & process_responses()