IoIiderp

libcurl example

Aug 8th, 2018
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. #include <iostream>
  2. #include <curl/curl.h>
  3.  
  4. // This function basically deals with the buffers of data returned when we make a HTTP GET request.
  5. size_t writefunc(char* data, size_t charsize, const size_t buffsize, std::string *ret)
  6. {
  7.     const size_t realsize = charsize * buffsize;
  8.  
  9.     // Convert data into a C string
  10.     char* cstr = new char[realsize+1];
  11.     for(size_t i = 0; i < realsize; ++i)
  12.         cstr[i] = data[i];
  13.     cstr[realsize] = '\0';
  14.  
  15.     // Create the return value
  16.     *ret += cstr;
  17.  
  18.     // We have to return this or else curl will throw an error.
  19.     return realsize;
  20. }
  21.  
  22. int main()
  23. {
  24.     std::string ret; // Our return value to the GET request, basically the HTTP page.
  25.  
  26.     CURL *curl; // This will be our curl request.
  27.  
  28.     // Initialise curl.
  29.     curl = curl_easy_init();
  30.     if(!curl)
  31.     {
  32.         std::cerr << "Error initialising curl!" << std::endl;
  33.         return 1;
  34.     }
  35.  
  36.     // Curl options.
  37.     curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");
  38.     curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, true);
  39.     curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc); // The function we use to deal with the stream of data.
  40.     curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ret); // Arguments passed onto the write function.
  41.  
  42.     // Execute it.
  43.     curl_easy_perform(curl);
  44.  
  45.     // Show the web page in text.
  46.     std::cout << ret << std::endl;
  47.  
  48.     // Clean up.
  49.     curl_easy_cleanup(curl);
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment