【发布时间】:2015-07-23 14:15:42
【问题描述】:
我正在尝试使用 curl 从 localhost 服务器下载一个 zip 文件
http://localhost:8080/zip/json.zip?assetIds=<comma-separated asset ids>
当我在浏览器上输入网址时,文件开始下载,没有问题。 所以当我尝试使用 curl 到一个已经存在的 zip 文件时:
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 文件变成了 EMPTY 文件,甚至不是 zip 文件:/ 有人知道出了什么问题吗?
【问题讨论】:
-
“当我在浏览器上输入 url 时,文件开始下载没有问题” 探索更多。真的会发生什么?有没有重定向? HTTP 请求和响应标头是什么?也许您需要在您的 C++ 实现中做更多的工作,以更好地模拟在您的浏览器中为该资源发生的 HTTP 事务。