直接上代码:
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
int http_get_upgrade_file(const char* file_name, const char* url)
{
CURL *curl;
CURLcode __attribute__ ((unused)) res;
FILE *fp;
curl = curl_easy_init();
int httpcode = -1;
if(curl)
{
fp = fopen(file_name,"wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
if(strstr(url,"https"))
{
curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
}
else
{
curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "http");
}
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 60L);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 60L);
res = curl_easy_perform(curl);
if(fp)
{
fclose(fp);
}
curl_easy_getinfo(curl, CURLINFO_HTTP_CODE, &httpcode);
curl_easy_cleanup(curl);
}
if (httpcode != 200)
{
printf("HttpCode error:%d try to check ip\n", httpcode);
return -1;
}
return 0;
}
判断是HTTP还是https这里不太严谨,不过正常使用问题不大。
标签:fp,文件,setopt,libcurl,CURLOPT,easy,curl,下载,size From: https://www.cnblogs.com/still-smile/p/16659244.html