How to get the HTTP response string using Curl in C++

Viewed 25969

I'm very new to HTTP commands and the libcurl library. I know how to get the HTTP response code but not the HTTP response string. Following is the code snippet that I wrote to get the response code. Any help on how to get the response string will be highly appreciated!!!

curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
CURLcode ret = curl_easy_perform(curl);

if (ret != CURLE_OK) {
    LOG(INFO) << "Failed to perform the request. "
              << "Return code: " << ret;
    return false;
}

std::unique_ptr<int64_t> httpCode(new int64_t);
// Get the last response code.
ret = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, httpCode.get());
if (ret != CURLE_OK) {
  LOG(INFO) << "curl_easy_getinfo failed to retrieve http code. "
            << "Return code: " << ret;
  return false;
}

I tried doing this as well to get the HTTP response string in readBuffer.

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

std::string readBuffer;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);

CURLcode ret = curl_easy_perform(curl);
cout << readBuffer << "\n";

But the readBuffer is empty. I don't understand where I am going wrong. Any pointers on how to solve this will be really nice!

2 Answers

For the numerical response code, getinfo with CURLINFO_RESPONSE_CODE is the way to go:

long response_code;
curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE,&response_code);

However there is no equivalent getinfo capture for the server's response text. If you need the server's text, inspect the raw HTTP headers. There are two ways to do this:

  1. Enable writing headers to the payload with CURLOPT_HEADER, then extract the headers from the combined payload, splitting the body on \n\n

  2. Set a header callback function with CURLOPT_HEADERFUNCTION and parse directly from that

Related