我尝试使用cURL库下载zip文件。这是我用来发出请求的代码:
const char* RestClient::user_agent = VERSION;
/** initialize authentication variable */
std::string RestClient::user_pass = std::string();
/** Authentication Methods implementation */
void RestClient::clearAuth(){
RestClient::user_pass.clear();}
void RestClient::setAuth(const std::string& user,const std::string& password){
RestClient::user_pass.clear();
RestClient::user_pass += user+":"+password;}
/** @brief HTTP GET method @param url to query @return response struct */
RestClient::response RestClient::get(const std::string& url){
RestClient::response ret = {};
CURL *curl = NULL;
CURLcode res = CURLE_OK;
curl = curl_easy_init();
if (curl) {
/** set basic authentication if present*/
if(RestClient::user_pass.length()>0){
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(curl, CURLOPT_USERPWD,RestClient::user_pass.c_str());
}
curl_easy_setopt(curl, CURLOPT_USERAGENT, RestClient::user_agent);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
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;}
write_callback:
size_t RestClient::write_callback(void *data, size_t size, size_t nmemb,void *userdata)
{ RestClient::response* r;
r = reinterpret_cast<RestClient::response*>(userdata);
r->body.append(reinterpret_cast<char*>(data), size*nmemb);
return (size * nmemb);}
HTTP请求应该是:
http://yourserver.com/zip/<filename>.zip?downloadKind=<original|preview>&assetIds=<comma-separated asset ids>
当我发送请求时:
RestClient::response response = RestClient::get("http://localhost:8080/zip/tesst.zip?downloadKind=original&assetIds=60ZRK8LQ4RW8CYeZSzFmi0");
我得到&#34; 200&#34;作为响应代码和&#34; PK&#34;作为回应机构。什么&#34; PK&#34;意思 ?我做错了什么?
答案 0 :(得分:3)
好的,问题有点缺乏细节,但我会猜测。
您的body
成员变量属于std::string
类型,不适合存储二进制数据。碰巧,ZIP文件通常以字节50 4b 03 04 xx 00
开头,所以如果你把它解释为C字符串,那么它们将以00
字节结束。
您可以使用std::vector<char>
作为body
的类型而不是std::string
。这将正确处理二进制数据。
PS:从技术上讲,std::string
可以处理嵌入的NUL字符,但我敢打赌。无论如何,这不是工作的正确工具。