libcurl实现获取内容长度、请求文件(断点续传)

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值