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);
43 for(
auto response : _responses ) {
44 std::get<1>(response)(std::get<0>(response));
55 const std::shared_ptr<httplib::Response> Client::_get_aux(std::string url) {
57 #if CPPHTTPLIB_OPENSSL_SUPPORT 60 httplib::SSLClient cli(parts.first.c_str(), 443);
61 return cli.Get(parts.second.c_str());
65 httplib::Client cli(parts.first.c_str(), 80);
66 return cli.Get(parts.second.c_str());
67 #if CPPHTTPLIB_OPENSSL_SUPPORT 72 void Client::_get_thread(std::string url, std::function<
void(json&)> handler) {
78 auto response = _get_aux(url);
80 if (response && response->status == 200) {
81 json_response = json::parse(response->body);
82 }
else if ( response ) {
83 std::cout <<
"Warning:: Elma client connected to " 85 <<
", which returned Error: " 89 std::cout <<
"Warning:: Elma client returned no result" 93 }
catch (
const httplib::Exception& e) {
94 std::cout <<
"Warning: Elma client failed: " 97 }
catch(
const json::exception& e ) {
98 std::cout <<
"Warning: Elma client could not parse response: " 102 std::cout <<
"Warning: Elma client failed with no message\n";
106 _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()