Created
October 4, 2018 09:29
-
-
Save dmthuc/792dfa0a9ad73a6c074999f676ac9dc6 to your computer and use it in GitHub Desktop.
Example of HTTP get with C curl library
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
/* Get bit-coin exchange rate */ | |
#include <iostream> | |
#include <memory> | |
#include <string> | |
#include <stdexcept> | |
#include <curl/curl.h> | |
using namespace std; | |
struct Curl_global | |
{ | |
Curl_global() | |
{ | |
curl_global_init(CURL_GLOBAL_ALL); | |
} | |
~Curl_global() | |
{ | |
curl_global_cleanup(); | |
} | |
}; | |
Curl_global global{}; | |
auto make_curl_easy_handle_wrapper() | |
{ | |
CURL *curl = curl_easy_init(); | |
if (!curl) { | |
throw runtime_error("fail to get curl easy handle"); | |
} | |
return unique_ptr<CURL, decltype(&curl_easy_cleanup)>{curl, &curl_easy_cleanup}; | |
} | |
size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp) | |
{ | |
string* str = static_cast<string*>(userp); | |
char* data = static_cast<char*>(buffer); | |
*str += data; | |
return size* nmemb; | |
} | |
string http_get(const string& url) | |
{ | |
string str_res; | |
auto curl_easy_handle_wrapper = make_curl_easy_handle_wrapper(); | |
CURL* curl = curl_easy_handle_wrapper.get(); | |
curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); | |
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); | |
curl_easy_setopt(curl, CURLOPT_WRITEDATA, str_res); | |
/* example.com is redirected, so we tell libcurl to follow redirection */ | |
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); | |
/* Perform the request, res will get the return code */ | |
CURLcode res = curl_easy_perform(curl); | |
/* Check for errors */ | |
if(res != CURLE_OK) | |
fprintf(stderr, "curl_easy_perform() failed: %s\n", | |
curl_easy_strerror(res)); | |
return str_res; | |
} | |
int main() | |
{ | |
auto res = http_get("https://blockchain.info/ticker"); | |
cout <<res<<'\n'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment