/* Example of using curl from C++. About curl: http://curl.haxx.se/libcurl/c/ Compilation on Linux: g++ -o curl-example -lcurl curl-example.cpp */ #include #include #include #include using std::cerr; using std::cout; using std::endl; using std::string; using std::stringstream; // vvvvvvvvv start: could be moved to separate header-file vvvvvvvvv class URL { private: CURL* curl; std::string url; void init_curl(); static size_t curl_callback(void*,size_t,size_t,void*); public: URL(std::string); ~URL(); void set_url(std::string); std::string get_url() const; std::string get_body() const; }; // ^^^^^^^^^ end: could be moved to separate header-file ^^^^^^^^^ URL::URL(string arg) { init_curl(); set_url(arg); } URL::~URL() { curl_easy_cleanup(curl); } void URL::init_curl() { curl = curl_easy_init(); if (0==curl) { cerr << "Couldn't initialize curl" << endl; exit(1); } curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION, curl_callback); } void URL::set_url(string arg) { url=arg; curl_easy_setopt(curl, CURLOPT_URL, arg.c_str()); } string URL::get_url() const { return url; } // Returns body of HTTP response string URL::get_body() const { stringstream ss; curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&ss); int err = curl_easy_perform(curl); if (err) { cerr << "could not grab url " << url; return ""; } else { return ss.str(); } } /* C <-> C++ "bridge". A callback with this signature is needed by curl. - See secion "CURLOPT_WRITEFUNCTION" at http://curl.haxx.se/libcurl/c/curl_easy_setopt.html */ size_t URL::curl_callback(void* source_p,size_t size, size_t nmemb, void* dest_p){ int realsize=size*nmemb; string chunk((char*)source_p,realsize); *((stringstream*)dest_p) << chunk; return realsize; } // Examples of use int main() { URL u("http://slashdot.org/"); cout << "From " << u.get_url() << ":" << endl << u.get_body() << endl; u.set_url("http://troels.arvin.dk/"); cout << "From " << u.get_url() << ":" << endl << u.get_body() << endl; }