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;
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With