若是但願獲取下載或者上傳進度相關信息,就給CURLOPT_NOPROGRESS屬性設置0值
int ret = curl_easy_setopt(easy_handle, CURLOPT_URL, "http://speedtest.wdc01.softlayer.com/downloads/test10.zip");
ret |= curl_easy_setopt(easy_handle, CURLOPT_NOPROGRESS, 0L);
設置一個回掉函數來獲取數據git
ret |= curl_easy_setopt(easy_handle, CURLOPT_XFERINFOFUNCTION, progress_callback);
progress_callback原型爲
int progress_callback(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow);
這個回調函數能夠告訴咱們有多少數據須要傳輸以及傳輸了多少數據,單位是字節。dltotal是須要下載的總字節數,dlnow是已經下載的字節數。ultotal是將要上傳的字節數,ulnow是已經上傳的字節數。若是你僅僅下載數據的話,那麼ultotal,ulnow將會是0,反之,若是你僅僅上傳的話,那麼dltotal和dlnow也會是0。clientp爲用戶自定義參數,經過設置CURLOPT_XFERINFODATA屬性來傳遞。此函數返回非0值將會中斷傳輸,錯誤代碼是CURLE_ABORTED_BY_CALLBACK
傳遞用戶自定義的參數,以CURL *easy_handle爲例github
ret |= curl_easy_setopt(easy_handle, CURLOPT_XFERINFODATA, easy_handle);
上面的下載可能有些問題,若是設置的URL不存在的話,服務器返回404錯誤,可是程序發現不了錯誤,仍是會下載這個404頁面。
這時須要設置CURLOPT_FAILONERROR屬性,當HTTP返回值大於等於400的時候,請求失敗服務器
ret |= curl_easy_setopt(easy_handle, CURLOPT_FAILONERROR, 1L);curl
progress_callback的實現
int progress_callback(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)
{
CURL *easy_handle = static_cast<CURL *>(clientp);
char timeFormat[9] = "Unknow";
// Defaults to bytes/second
double speed;
string unit = "B";
curl_easy_getinfo(easy_handle, CURLINFO_SPEED_DOWNLOAD, &speed); // curl_get_info必須在curl_easy_perform以後調用
if (speed != 0)
{
// Time remaining
double leftTime = (downloadFileLength - dlnow - resumeByte) / speed;
int hours = leftTime / 3600;
int minutes = (leftTime - hours * 3600) / 60;
int seconds = leftTime - hours * 3600 - minutes * 60;
#ifdef _WIN32
sprintf_s(timeFormat, 9, "%02d:%02d:%02d", hours, minutes, seconds);
#else
sprintf(timeFormat, "%02d:%02d:%02d", hours, minutes, seconds);
#endif
}
if (speed > 1024 * 1024 * 1024)
{
unit = "G";
speed /= 1024 * 1024 * 1024;
}
else if (speed > 1024 * 1024)
{
unit = "M";
speed /= 1024 * 1024;
}
else if (speed > 1024)
{
unit = "kB";
speed /= 1024;
}
printf("speed:%.2f%s/s", speed, unit.c_str());
if (dltotal != 0)
{
double progress = (dlnow + resumeByte) / downloadFileLength * 100;
printf("\t%.2f%%\tRemaing time:%s\n", progress, timeFormat);
}
return 0;
}
整個工程的GitHub地址:https://github.com/forzxy/HttpClient函數
---------------------
做者:小丑魚_y
來源:CSDN
原文:https://blog.csdn.net/ixiaochouyu/article/details/47301005
版權聲明:本文爲博主原創文章,轉載請附上博文連接!url