C++ 用curl解压gzip数据
我添加了C++ 用curl解压gzip数据,c++,curl,libcurl,C++,Curl,Libcurl,我添加了curl\u easy\u setopt(客户端,CURLOPT\u编码,“gzip”)到我的代码 我希望curl能够使服务器发送压缩数据并对其进行解压缩 实际上,我在HTTP头中看到数据被压缩(Vary:Accept Encoding) 内容编码:gzip),但curl并没有为我解压 是否有其他命令可用于此操作?请注意,此选项已重命名为 如文件所述: 设置HTTP请求中发送的Accept Encoding:标头的内容,并在接收到Content Encoding:标头时启用响应解码 因此
curl\u easy\u setopt(客户端,CURLOPT\u编码,“gzip”)代码>到我的代码
我希望curl能够使服务器发送压缩数据并对其进行解压缩
实际上,我在HTTP头中看到数据被压缩(Vary:Accept Encoding)
内容编码:gzip),但curl并没有为我解压
是否有其他命令可用于此操作?请注意,此选项已重命名为
如文件所述:
设置HTTP请求中发送的Accept Encoding:标头的内容,并在接收到Content Encoding:标头时启用响应解码
因此,它确实解码(即解压缩)响应。支持三种编码:“identity”
(不执行任何操作)、“zlib”
和“gzip”
。或者,您可以传递一个空字符串,该字符串创建一个包含所有支持的编码的接受编码:
头
最后,测试它很方便,因为它包含一个返回gzip内容的专用端点。下面是一个例子:
#include <curl/curl.h>
int
main(void)
{
CURLcode rc;
CURL *curl;
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, "http://httpbin.org/gzip");
curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "gzip");
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
rc = curl_easy_perform(curl);
curl_easy_cleanup(curl);
return (int) rc;
}
并得到如下响应:
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Encoding: gzip
Content-Type: application/json
...
JSON响应(因此被解压)写在标准输出上。c++CURL库不会压缩/解压数据。你必须自己做
CURL *curl = curl_easy_init();
struct curl_slist *headers=NULL;
headers = curl_slist_append(headers, "Accept: application/json");
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "Content-Encoding: gzip");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers );
curl_easy_setopt(curl, CURLOPT_ENCODING, "gzip");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, zipped_data.data() );
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, zipped_data.size() );
下载错误(如前一条注释所述),上载正确(因为HTTP不压缩上载)。如果使用CURLOPT_HTTPHEADER指定Accept Encoding标头,libcurl将不会执行任何压缩/解压缩。但是如果您使用CURLOPT_ACCEPT_编码,libcurl将为您做一切。看见
CURL *curl = curl_easy_init();
struct curl_slist *headers=NULL;
headers = curl_slist_append(headers, "Accept: application/json");
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "Content-Encoding: gzip");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers );
curl_easy_setopt(curl, CURLOPT_ENCODING, "gzip");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, zipped_data.data() );
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, zipped_data.size() );