views:

467

answers:

2

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;
 }
+1  A: 

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.

Tim Yates
I already was in that link but I couldn't understand how to do that, with the pointers and all.and the file thing isn't good for me, because I have a small amount of data and I need it to be very fast..
shaimagz
I don't blame you. See my edit.
Tim Yates
+1  A: 

Here is an example for you http://code.google.com/p/aws4c/source/browse/trunk/aws4c.c#637.

T.Yates is right, you have to make a function that will receive the data. And let CURL know about your function using CURLOPT_WRITEFUNCTION.

Vlad
can you tell me how to do that with a little more details? like where to put CURLOPT_WRITEFUNCTION ?
shaimagz