user2769274 user2769274 - 1 year ago 211
C++ Question

Retrieving response text from curl in cpp

we need to receive response string from curl in CPP ,I tried following options but nothing worked.js uses xhr.responseText for this.I need to do in cpp.

static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
size_t realsize = size * nmemb;
const char* sp = static_cast<const char*>(contents);
readBuffer.append(sp, realsize);
return realsize;

CURLcode res;
char* http_error= new char[100];

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
code = curl_easy_perform(curl);
cout << "Curl response msg CURLOPT_WRITEDATA: "<<curl_easy_strerror(code)<< " respose :"<<readBuffer;

res=curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code) ;
cout << "Curl response msg: "<< curl_easy_strerror(res);

huu huu
Answer Source

Change your WriteCallback function to this:

size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) {
    userp->append((char*) contents, size * nmemb);
    return size * nmemb;

Remember, you are passing in &readBuffer as the CURL_WRITEDATA option. This shows up as the fourth parameter in the WriteCallback. Since the type of &readBuffer is std::string*, you can use that as the signature in your callback.

Additionally, since it's a std::string* and not a std::string, you have to access append through the pointer, hence the -> instead of .. After curl_easy_perform, readBuffer should hold the response from the curl request.

To get the response code, you can grab that after making the request:

long http_code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download