繁体   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