如何使用 libcurl 从 github 存储库下载 zip 文件?

Ces*_*sar 1 c++ windows curl libcurl

我已将zip包含 txt 文件的 WinRAR 压缩文件上传到我的 github 测试存储库中,如何zip使用下载该文件curl

我试过:

    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");
Run Code Online (Sandbox Code Playgroud)

CURLCode res返回 (CURLE_OK) 但它创建了一个文件data.zip0 bytes出了什么问题?

Dan*_*erg 7

问题

我检查过

curl -I https://github.com/R3uan3/test/files/9544940/test.zip
Run Code Online (Sandbox Code Playgroud)

它得到

HTTP/2 302
...
location: https://objects.githubusercontent.com/github-production-rep...
Run Code Online (Sandbox Code Playgroud)

换句话说:这是一个重定向,并且您没有要求 libcurl 遵循重定向 - 因此您只能获得存储的第一个响应(其具有零字节主体)。

修复

您可以通过将此行添加到代码中来使 libcurl 遵循重定向:

curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1L);
Run Code Online (Sandbox Code Playgroud)