How to use libcurl in C++ with std::string

#include <curl/curl.h> #include <curl/types.h> #include <curl/easy.h> class MyClass { public: std::string get_html(std::string website); static size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp); }; size_t MyClass::write_data(void *buffer, size_t size, size_t nmemb, void *userp) { char *d = (char*)buffer; std::string *b = (std::string *)(userp); int result = 0; if (b != NULL) { b->append(d, size * nmemb); result = size * nmemb; } return result; } std::string MyClass::get_html(std::string website) { std::string curl_buffer = ""; CURL *curl; CURLcode curl_result; curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, website.c_str()); // website example: http://www.google.com/ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &MyClass::write_data); // our static function curl_easy_setopt(curl, CURLOPT_WRITEDATA, &curl_buffer); // the string which will contain the html curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); // required if curl should follow basic redirects curl_result = curl_easy_perform(curl); curl_easy_cleanup(curl); if (curl_result == CURLE_OK) { // everything went okay and our html is in curl_buffer, you can output result if you want std::cout << curl_buffer << std::endl; } else { // something went wrong - error code is in curl_result std::cout << "libcurl error code #" << curl_result << std::endl; } } return curl_buffer; } size_t MyClass::write_data(void *buffer, size_t size, size_t nmemb, void *userp) { char *d = (char*)buffer; std::string *b = (std::string *)(userp); int result = 0; if (b != NULL) { b->append(d, size * nmemb); result = size * nmemb; } return result; }

 

Come from : How to use libcurl in C++ with std::string

你可能感兴趣的:(html,C++,String,buffer,include,website)