libcurl HTTP request to save respond into variable - c++

shaimagz picture shaimagz · Mar 4, 2010 · Viewed 15.1k times · Source

I'm trying to save the returned data from HTTP request into a variable.

The code below will automatically print the respond of the request, but I need it to save the respond to a char or string.

int main(void)
{
        char * result;
        CURL *curl;
        CURLcode res;
        curl = curl_easy_init();
        if(curl) {
            curl_easy_setopt(curl, CURLOPT_URL, "http://www.browsarity.com/");

            res = curl_easy_perform(curl);
            curl_easy_cleanup(curl);
        }
        return 0;
 }

Answer

Tim Yates picture Tim Yates · Mar 4, 2010

I think you will have to write a function to pass as a write callback via CURLOPT_WRITEFUNCTION (see this). Alternatively you could create a temporary file and pass its file descriptor via CURLOPT_WRITEDATA (the next option listed on that page). Then you would read back the data from the temporary file into a string. Not the prettiest of solutions, but at least you don't have to mess with buffers and function pointers.

EDIT: Since you don't want to write to a file, something like this might work:

#include <string>

size_t write_to_string(void *ptr, size_t size, size_t count, void *stream) {
  ((string*)stream)->append((char*)ptr, 0, size*count);
  return size*count;
}

int main(void) {
  // ...
  if (curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "http://www.browsarity.com/");

    string response;
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_to_string);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);

    // The "response" variable should now contain the contents of the HTTP response
  }
  return 0;
}

DISCLAIMER: I haven't tested this, and I'm a bit rusty on C++, but you can try it out.