HttpClient.cpp
Go to the documentation of this file.
00001 
00011 // worldlib
00012 #include "worldlib/remote/HttpClient.h"
00013 
00014 // ROS
00015 #include <ros/ros.h>
00016 
00017 using namespace std;
00018 using namespace rail::spatial_temporal_learning::worldlib::remote;
00019 
00020 HttpClient::HttpClient(const HttpClient &client) : Client(client.getHost(), client.getPort())
00021 {
00022   // initialize the client
00023   this->init();
00024 }
00025 
00026 HttpClient::HttpClient(const string &host, const uint16_t port) : Client(host, port)
00027 {
00028   // initialize the client
00029   this->init();
00030 }
00031 
00032 HttpClient::~HttpClient()
00033 {
00034   // check for an existing connection
00035   if (curl_ != NULL)
00036   {
00037     curl_easy_cleanup(curl_);
00038   }
00039 }
00040 
00041 void HttpClient::init()
00042 {
00043 
00044   // create the base URL
00045   stringstream ss;
00046   ss << "http://" << this->getHost() << ":" << this->getPort() << "/";
00047   base_ = ss.str();
00048 
00049   // initialize cURL
00050   curl_ = curl_easy_init();
00051   // follow redirects
00052   curl_easy_setopt(curl_, CURLOPT_FOLLOWLOCATION, 1L);
00053   // set up the read into the buffer
00054   curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, curlWriteFunction);
00055 }
00056 
00057 string HttpClient::get(const std::string &url) const
00058 {
00059   // create the URL
00060   string full_url = base_ + url;
00061   curl_easy_setopt(curl_, CURLOPT_URL, full_url.c_str());
00062 
00063   // create a buffer
00064   string buffer;
00065   curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &buffer);
00066 
00067   // perform the request and check for errors
00068   CURLcode result = curl_easy_perform(curl_);
00069   if (result != CURLE_OK)
00070   {
00071     ROS_ERROR("HTTP Error: %s", curl_easy_strerror(result));
00072     buffer.clear();
00073   } else
00074   {
00075     // check if we had a valid response
00076     long code;
00077     curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE, &code);
00078     if (code != 200)
00079     {
00080       ROS_ERROR("HTTP Error: %s returned Error Code %li.", full_url.c_str(), code);
00081       buffer.clear();
00082     }
00083   }
00084 
00085   return buffer;
00086 }
00087 
00088 static size_t rail::spatial_temporal_learning::worldlib::remote::curlWriteFunction(const void *contents,
00089     const size_t size, const size_t num, void *buffer)
00090 {
00091   // get the size of contents
00092   size_t contents_size = size * num;
00093   // store the result in the buffer
00094   ((string *) buffer)->append((char *) contents, contents_size);
00095   return contents_size;
00096 }


worldlib
Author(s): Russell Toris
autogenerated on Fri Feb 12 2016 00:24:18