libcurl downloads no data to buffer

Viewed 326

I am using following code to download data from an url to memory (stream). Around 2% chance, the size of the stream is zero. I can download proper data from the same failing url if I try it another time. I am not sure if this is a network issue, CPU usage issue, or it's just the code not covering some corner cases. Please advice. Thanks!

static size_t write_data(char *ptr, size_t size, size_t nmemb, void *userdata)
{
    std::vector<uchar> *stream = (std::vector<uchar>*)userdata;
    size_t count = size * nmemb;
    stream->insert(stream->end(), ptr, ptr + count);
    return count;
}

static void CurlUrl(const char* img_url, std::vector<uchar>* stream) {
    CURL *curl = curl_easy_init(); // curl_global_init is called eleswhere.
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
    curl_easy_setopt(curl, CURLOPT_URL, img_url);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, stream);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
    CURLcode res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
}
1 Answers

If it didn't deliver any download data into the buffer via the callback, it means that the transfer either failed or that there was exactly zero bytes to transfer.

  1. Check the return code from curl_easy_perform() as it might actually tell you exactly what happened.
  2. Use CURLOPT_VERBOSE to see what's going on if (1) is not enough.
  3. Use CURLOPT_ERRORBUFFER to get a better error description if it fails if (2) is not enough.
Related