c++ - 如何使用 libcurl 从 github repo 下载 zip 文件?

标签 c++ windows curl libcurl

我已经上传了一个用 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/

相关文章:

c++ - 使用基于 bool 值的两种方法之一调用方法时如何确保避免分支预测错误

windows - 如何使用批处理文件在 Windows 下为 Perl 程序创建快捷方式?

Windows API 和 SendMessage()

java - 使用 netsh 从 Java 访问 Wi-Fi 网络接口(interface)详细信息

apache - 什么是 Apache 的 OpenSSL 以及为什么一台服务器有它而另一台没有

c++ - 双向链表添加元素

c++ - 检索数据结构对齐信息

c++ - "Remember the milk"订阅日历的 Google 日历同步问题

php - 在 phantomjs 中获取 POST 数据作为对象?

python - 指示 Scrapy 忽略站点的内容长度