本节jwisp为你们举例说明若是使用上节介绍的函数和参数,在使用libcurl的过程当中,如何获取下载目标文件的大小 , 下载进度条,断点续传等,这些基本的函数,将为jwisp在最后处理下载过程异常中断等问题提供支持.java
1. 编写获得下载目标文件的大小的函数curl
long getDownloadFileLenth(const char *url){
long downloadFileLenth = 0;
CURL *handle = curl_easy_init();
curl_easy_setopt(handle, CURLOPT_URL, url);
curl_easy_setopt(handle, CURLOPT_HEADER, 1); //只须要header头
curl_easy_setopt(handle, CURLOPT_NOBODY, 1); //不须要body
if (curl_easy_perform(handle) == CURLE_OK) {
curl_easy_getinfo(handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &downloadFileLenth);
} else {
downloadFileLenth = -1;
}
return downloadFileLenth;
}
2. 下载中回调本身写的获得下载进度值的函数函数
下载回调函数的原型应该为:url
int progressFunc(const char* flag, double dtotal, double dnow, double ultotal, double ulnow);
.net
a. 应该在外部声明一个远程下载文件大小的全局变量orm
double downloadFileLenth = 0;
blog
为了断点续传, 还应该声明一个本地文件大小的全局变量get
double localFileLenth = 0;
原型
b. 编写一个获得进度值的函数getProgressValue()回调函数
int getProgressValue(const char* flag, double dt, double dn, double ult, double uln){
double showTotal, showNow;
if (downloadFileLenth == 0){
downloadFileLenth = getDownloadFileLenth(url);
}
showTotal = downloadFileLenth;
if (localFileLenth == 0){
localFileLenth = getLocalFileLenth(filePath);
}
showNow = localFileLenth + dn;
//而后就能够调用你本身的进度显示函数了, 这里假设已经有一个进度函数, 那么只须要传递当前下载值和总下载值便可.
showProgressValue(showNow, showTotal);
}
c. 在下载中进行三个下载参数的设置
curl_easy_setopt(handle, CURLOPT_NOPROGRESS, 0);
curl_easy_setopt(handle, CURLOPT_PROGRESSFUNCTION, getProgressValue); //设置回调的进度函数
curl_easy_setopt(handle, CURLOPT_PROGRESSDATA, “flag”); //此设置对应上面的const char *flag
3. 断点续传
用libcurl实现断点续传很简单,只用两步便可实现,一是要获得本地文件已下载的大小,经过函数getLocalFileLenth()方法来获得,二是设置CURLOPT_RESUME_FROM_LARGE参数的值为已下载本地文件大小.
获得本地文件大小的函数:
long getLocalFileLenth(const char* localPath);
设置下载点以下便可:
curl_easy_setopt(handle, CURLOPT_RESUME_FROM_LARGE, getLocalFileLenth(localFile));