static size_t curl_writeFileCallback(void *ptr, size_t size, size_t nmemb, void *stream)
{
return fwrite(ptr, size, nmemb, stream);
}
int curlApi_download(char *url, char *filePath)
{
CURL *curl = NULL;
CURLcode code = 0;
double conLen = 0;
long downloadedSize = 0;
int ret = 0;
long finalSize = 0;
long response_code = -1;
curl = curl_easy_init();
if(NULL == curl)
{
return -1;
}
FILE *fp = fopen(filePath, "ab+");
if (NULL == fp)
{
perror("fopen failed.\n");
return -1;
}
fseek(fp, 0, SEEK_END);
downloadedSize = ftell(fp);
printf("downloadedSize : %ld \n", downloadedSize);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER,0L);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3);
//curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3); //执行请求的最长等待时间,应大于CURLOPT_CONNECTTIMEOUT,下载大文件不设置
//curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);//调试用,1开启打印curl输出信息
//curl_easy_setopt(curl, CURLOPT_NOBODY, 1); //不请求body
//设置http 头部处理函数,获取内容长度
//curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, mqttCom_curlGetConLenCallback);
//curl_easy_setopt(curl, CURLOPT_HEADERDATA, &conLen);
//设置保存文件回调
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);//写报文内容到fp
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, mqttCom_WriteFileCallback);
//设置文件续传的位置
curl_easy_setopt(curl, CURLOPT_RESUME_FROM_LARGE, downloadedSize);//断点续传参数
//请求数据
code = curl_easy_perform(curl);
if(code != CURLE_OK)
{
printf("curl_easy_perform code: %d, %s\n", code, curl_easy_strerror(code));
ret = -1;
}
else
{
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
if(200 != response_code)
{
Console_Msg("response_code:%ld != 200\n", response_code);
ret = -1;
}
if (curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &conLen) != CURLE_OK)
{
printf("get content-length failed.");
ret = -1;
}
}
if (-1 != ret)
{
printf("content-length : %f\n", conLen);
finalSize = ftell(fp);
if ((finalSize - downloadedSize) == (long)conLen)
{
printf("download completed.\n");
}
else
{
printf("download failed, conLen:%ld, downloaded size:%ld\n", (long)conLen, downloadedSize);
ret = -1;
}
}
curl_easy_cleanup(curl);
curl = NULL;
fclose(fp);
fp = NULL;
return ret;
}
libcurl实现获取内容长度、请求文件(断点续传)
于 2022-04-02 15:10:52 首次发布