我已经上传了一个用 WinRAR 压缩的包含 txt 文件的 zip
文件到我的 github 测试 Repo ,如何使用 curl
下载 zip
文件?
我试过:
static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
size_t written = fwrite(ptr, size, nmemb, (FILE *)stream);
return written;
}
void Download(std::string url)
{
CURL *curl_handle;
static const char *pagefilename = "data.zip";
FILE *pagefile;
curl_global_init(CURL_GLOBAL_ALL);
/* init the curl session */
curl_handle = curl_easy_init();
/* set URL to get here */
curl_easy_setopt(curl_handle, CURLOPT_URL, url.c_str());
/* Switch on full protocol/debug output while testing */
curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L);
/* disable progress meter, set to 0L to enable and disable debug output */
curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 1L);
/* send all data to this function */
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data);
/* open the file */
pagefile = fopen(pagefilename, "wb");
if(pagefile) {
/* write the page body to this file handle */
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, pagefile);
/* get it! */
CURLCode res;
res = curl_easy_perform(curl_handle);
/* close the header file */
fclose(pagefile);
}
/* cleanup curl stuff */
curl_easy_cleanup(curl_handle);
curl_global_cleanup();
return;
}
Download("https://github.com/R3uan3/test/files/9544940/test.zip");
CURLCode res
返回 (CURLE_OK) 但它创建了一个 0 字节
的文件 data.zip
,有什么问题吗?
最佳答案
问题
我检查过
curl -I https://github.com/R3uan3/test/files/9544940/test.zip
得到
HTTP/2 302
...
location: https://objects.githubusercontent.com/github-production-rep...
换句话说:这是一个重定向,并且您没有要求 libcurl 遵循重定向 - 因此您只会存储第一个响应(其正文为零字节)。
修复
您可以通过将此行添加到您的代码中来使 libcurl 跟随重定向:
curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1L);
关于c++ - 如何使用 libcurl 从 github repo 下载 zip 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73685070/