libcurl下載文件


一、初始化

CURL *pHandler = curl_easy_init();

 

二、設置請求參數;

調用curl_easy_setopt方法,設置選項

curl_easy_setopt(pHandler , CURLOPT_WRITEFUNCTION, WriteData);

curl_easy_setopt(pHandler , CURLOPT_WRITEDATA, pFile);

 

//設置請求的url地址

curl_easy_setopt(pHandler , CURLOPT_URL, strUrl.c_str());

//如果為post請求,這里設置提交的參數

//curl_easy_setopt(pHandler , CURLOPT_POSTFIELDS, strPostData.c_str());

curl_easy_setopt(pHandler , CURLOPT_FAILONERROR, true);
curl_easy_setopt(pHandler , CURLOPT_TIMEOUT, 60);  //超時時間(秒)
curl_easy_setopt(pHandler , CURLOPT_NOSIGNAL, true);

 

三、執行下載

CURLcode codeRet = curl_easy_perform(pHandler);

 

四、獲取返回的http狀態碼

long retcode = 0;

curl_easy_getinfo(pHandler, CURLINFO_RESPONSE_CODE , &retcode);

 

五、清理

curl_easy_cleanup(pHandler);

 

if (codeRet == CURLE_OK && (retcode == 200 || retcode == 304 || retcode == 204))

{

//下載成功

}

else

{

//下載失敗

}

 

size_t WriteData(const char *ptr, size_t size, size_t nmemb, FILE *stream)
{
    if (!ptr || !stream)
    {
        return 0;
    }


    return fwrite(ptr, size, nmemb, stream);
}

 

關於文件的讀寫操作,可以參考這里:

fopen

fseek

ftell

fread

fwrite


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM