Last active
August 29, 2015 14:18
-
-
Save janpipek/4d82cf326956ef742820 to your computer and use it in GitHub Desktop.
Simple C++ wrapper around libcurl HTTP GET
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <curl/curl.h> | |
#include <string> | |
class HttpRequest { | |
public: | |
HttpRequest(const std::string& url) : _url(url) { } | |
const std::string getResponse() { | |
doIt(); | |
return _buffer; | |
} | |
private: | |
const std::string _url; | |
std::string _buffer; | |
static int writeMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp); | |
void doIt(); | |
}; | |
void HttpRequest::doIt() { | |
_buffer = ""; | |
CURL *curl; | |
CURLcode res; | |
curl = curl_easy_init(); | |
if (curl) { | |
curl_easy_setopt(curl, CURLOPT_URL, _url.c_str()); | |
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeMemoryCallback); | |
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)this); | |
res = curl_easy_perform(curl); | |
if(res != CURLE_OK) | |
fprintf(stderr, "curl_easy_perform() failed: %s\n", | |
curl_easy_strerror(res)); | |
curl_easy_cleanup(curl); | |
} | |
} | |
int HttpRequest::writeMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { | |
HttpRequest* request = (HttpRequest*)userp; | |
request->_buffer.append((char*) contents, size * nmemb); | |
return size * nmemb; | |
} | |
__attribute__((constructor)) void init() { | |
// Not thread-safe! | |
curl_global_init(CURL_GLOBAL_ALL); | |
} | |
__attribute__((destructor)) void fini() { | |
// Not thread-safe, but anyway, who cares... | |
curl_global_cleanup(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment