Skip to content

Instantly share code, notes, and snippets.

@vladon
Created August 21, 2015 08:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vladon/9e435ca4c85c9964d8ff to your computer and use it in GitHub Desktop.
Save vladon/9e435ca4c85c9964d8ff to your computer and use it in GitHub Desktop.
How to download from url and return contents as a string (using libcurl)
#include "http_client.h"
#include <memory>
std::string http_client::get_from_url(const std::string & a_url)
{
std::string result;
auto curl_deleter = [](CURL * curl_easy_handle)
{
curl_easy_cleanup(curl_easy_handle);
};
std::unique_ptr<CURL, decltype(curl_deleter)> curl_handle(curl_easy_init(), curl_deleter);
curl_easy_setopt(curl_handle.get(), CURLOPT_URL, a_url.c_str());
curl_easy_setopt(curl_handle.get(), CURLOPT_WRITEFUNCTION, http_client::curl_writefunction_callback);
curl_easy_setopt(curl_handle.get(), CURLOPT_WRITEDATA, &result);
CURLcode curl_easy_perform_result = curl_easy_perform(curl_handle.get());
return result;
}
size_t http_client::curl_writefunction_callback(void * a_buffer, size_t a_size, size_t a_nmemb, void * a_userp)
{
size_t resulting_size = a_size * a_nmemb;
std::string * result_string = static_cast<std::string *>(a_userp);
char * buffer_char_ptr = static_cast<char *>(a_buffer);
try {
result_string->append(buffer_char_ptr, resulting_size);
}
catch (const std::length_error&) {
return 0;
}
return resulting_size;
}
#ifndef HTTP_CLIENT_H
#define HTTP_CLIENT_H
#include <string>
#include <curl/curl.h>
class http_client
{
public:
static std::string get_from_url(const std::string& a_url);
private:
static size_t curl_writefunction_callback(void * a_buffer, size_t a_size, size_t a_nmemb, void * a_userp);
};
#endif HTTP_CLIENT_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment