仓库地址:
简介
cpr_range_download
项目使用CPR库来实现HTTP文件下载。它支持范围下载(Range)和断点续传功能。这意味着如果下载过程中断,程序可以从中断点继续下载,避免重新开始下载整个文件,从而节省时间和带宽。
使用的库
- CPR: 一个现代化的C++ HTTP请求库,简化了HTTP请求的处理。
- Boost.Filesystem: 提供文件系统操作的跨平台库。
主要代码
代码解释
#include <iostream>
#include <fstream>
#include <cpr/cpr.h>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
using namespace std;
这些是包含必要库的头文件。boost::filesystem
用于文件路径处理,cpr
用于HTTP请求。
bool downloadFile(const std::string& url, const std::string& filename)
{
static uint64_t s_totalSize = 0;
std::string tmp_filename = filename + ".tmp";
std::ofstream of(tmp_filename, std::ios::binary | std::ios::app);
auto pos = of.tellp();
std::cout << "of.tellp: " << pos << std::endl;
定义了downloadFile
函数,负责实际的文件下载。首先声明了一个静态变量totalSize
来跟踪已下载的总字节数。创建一个临时文件用于存储下载的数据,如果下载完成则重命名为最终文件名。
cpr::Url cpr_url{url};
cpr::Session s;
s.SetVerifySsl(cpr::VerifySsl{false});
s.SetUrl(cpr_url);
创建CPR会话对象并设置URL和SSL验证选项(此处禁用了SSL验证)。
auto fileLength = s.GetDownloadFileLength();
s.SetRange(cpr::Range{pos, fileLength - 1});
获取文件长度并设置HTTP Range头,以便从指定位置开始下载文件。
cpr::Response response = s.Download(of);
s_totalSize += response.downloaded_bytes;
std::cout << "response.status_code: " << response.status_code
<< ", response.downloaded_bytes: " << response.downloaded_bytes
<< std::endl;
if (s_totalSize >= fileLength)
{
s_totalSize = 0;
rename(tmp_filename.c_str(), filename.c_str());
return true;
}
return false;
}
执行文件下载并将数据写入临时文件中。检查是否所有文件数据已下载完毕,如果是,则重命名临时文件为最终文件名。
主函数
int main()
{
std::string url = "http://192.21.1.61:9001/download/test11.zip";
boost::filesystem::path p(url);
std::string filename = p.filename().c_str();
bool success = false;
while (!success)
{
success = downloadFile(url, filename);
}
std::cout << "done! " << std::endl;
return 0;
}
主函数设置要下载的URL和文件名。通过boost::filesystem
库提取文件名。调用downloadFile
函数进行下载,直到下载成功。