簡體   English   中英

如何使用 libcurl 從 github 存儲庫下載 zip 文件?

[英]How to download a zip file from a github repo using libcurl?

I have upload a zip file compressed with WinRAR containing a txt file into my github test Repo , how I could download the zip file using 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");

CURLCode res返回 (CURLE_OK) 但它創建了一個文件data.zip of 0 bytes ,怎么了?

問題

我檢查過

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM