1

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];

readBuffer.clear();
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
CURLcode code(CURLE_FAILED_INIT);
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);
melpomene
  • 84,125
  • 8
  • 85
  • 148
Ek1234
  • 407
  • 3
  • 7
  • 17

1 Answers1

3

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);
huu
  • 7,032
  • 2
  • 34
  • 49
  • Hi..thanks for replying..inside userp->append((char*) ptr, size * nmemb); ptr is sp(contents)? – Ek1234 Aug 03 '16 at 11:41
  • Oops, mistyped it. I'll correct it. You're right, it's supposed to be contents. – huu Aug 04 '16 at 18:11