簡體   English   中英

使用curl下載zip文件(C ++)

[英]Downloading zip file using curl (c++)

我正在嘗試使用curl從本地服務器下載zip文件

http://localhost:8080/zip/json.zip?assetIds=<comma-separated asset ids>

當我在瀏覽器中鍵入URL時,文件開始下載而沒有問題。 因此,當我嘗試對已有的zip文件使用curl時:

RestClient::response RestClient::get(const std::string& url)
{
  RestClient::response ret = {};


  CURL *curl = NULL;
  CURLcode res = CURLE_OK;
  FILE *fp
  curl = curl_easy_init();

  if (curl)
  {
       curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
       char outfilename[FILENAME_MAX] = "/Users/stage/Documents/temp/json.zip";
        fp = fopen(outfilename,"wb");

        curl_easy_setopt(curl, CURLOPT_CAINFO, "./ca-bundle.crt");
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);

        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, RestClient::write_data);

        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);


        int i=fclose(fp);
        if( i==0)
            system("unzip -j json.zip");

    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, RestClient::write_callback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ret);
    curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, RestClient::header_callback);
    curl_easy_setopt(curl, CURLOPT_HEADERDATA, &ret);
    res = curl_easy_perform(curl);
    if (res != CURLE_OK)
    {
      ret.body = "Failed to query.";
      ret.code = -1;
      return ret;
    }
    long http_code = 0;
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
    ret.code = static_cast<int>(http_code);

    curl_easy_cleanup(curl);
    curl_global_cleanup();
  }

  return ret;
}

以及寫入文件的功能

size_t RestClient::write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    return fwrite(ptr, size, nmemb, stream);
}

當我運行代碼時,我收到一條消息:

Archive:  json.zip
End-of-central-directory signature not found.  Either this file is not
a zipfile, or it constitutes one disk of a multi-part archive.  In the
latter case the central directory and zipfile comment will be found on
the last disk(s) of this archive.
unzip:  cannot find zipfile directory in one of json.zip or
    json.zip.zip, and cannot find json.zip.ZIP, period.

曾經包含圖像的json.zip文件甚至是zip都變成了EMPTY文件:/有人知道出了什么問題嗎?

我的腳本(不是C ++)中的curl命令遇到了完全相同的問題。 我最終查看了在文本編輯器中下載的.zip文件,發現該文件包含HTML錯誤消息,而不是我認為自己下載的實際文件。 然后,我在腳本中進行了一些調試,並將創建的URL復制並粘貼到瀏覽器中。 當我檢查URL時,我得到了相同的錯誤消息。

長話短說,我的網址輸入有誤。 我冒昧地猜測您遇到了非常相似的問題。

但是,就我而言,這就像調用shell命令“ curl -o”一樣容易,您的C ++代碼似乎比我所做的要復雜。

我希望這會以同樣的方式有所幫助。

暫無
暫無

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

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