我在我的代码中添加了 curl_easy_setopt(client, CURLOPT_ENCODING, "gzip");
。
我预计 curl 会导致服务器发送压缩数据并对其进行解压缩。
实际上我在 HTTP header 中看到数据已压缩(变化:Accept-Encoding 内容编码:gzip),但 curl 不会为我解压缩它。
我应该为此使用其他命令吗?
最佳答案
请注意,此选项已重命名为 CURLOPT_ACCEPT_ENCODING
.
如文档所述:
Sets the contents of the Accept-Encoding: header sent in a HTTP request, and enables decoding of a response when a Content-Encoding: header is received.
因此它确实解码(即解压缩)响应。支持三种编码:"identity"
(什么都不做)、"zlib"
和 "gzip"
。或者,您可以传递一个空字符串,它会创建一个包含所有支持的编码的 Accept-Encoding:
header 。
最后,httpbin测试它很方便,因为它包含一个返回 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;
}
它发送:
GET /gzip HTTP/1.1
Host: httpbin.org
Accept: */*
Accept-Encoding: gzip
并得到响应:
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Encoding: gzip
Content-Type: application/json
...
然后将 JSON 响应(因此解压缩)写入标准输出。
关于c++ - 使用 curl 解压 gzip 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20781856/