Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
 }
like image 527
shaimagz Avatar asked Mar 04 '10 04:03

shaimagz


2 Answers

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.

like image 186
Tim Yates Avatar answered Nov 15 '22 19:11

Tim Yates


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.

like image 30
Vlad Avatar answered Nov 15 '22 17:11

Vlad