使用 curl 解压缩 gzip 数据

decompression gzip data with curl

本文关键字:数据 gzip 解压缩 curl 使用      更新时间:2023-10-16

我在代码中添加了curl_easy_setopt(client, CURLOPT_ENCODING, "gzip");

我希望 curl 会导致服务器发送压缩数据并解压缩它。

实际上我在HTTP标头中看到数据被压缩(变化:接受编码)内容编码:gzip),但 curl 不会为我解压缩它。

我应该为此使用其他命令吗?

请注意,此选项已重命名为 CURLOPT_ACCEPT_ENCODING

如文档所述:

设置在 HTTP 请求中发送的 Accept-Encoding: 标头的内容,并在收到 Content-Encoding: 标头时启用响应的解码。

因此,它确实解码(即解压缩)响应。支持三种编码:"identity"(不执行任何操作)、"zlib""gzip" 。或者,您可以传递一个空字符串,该字符串创建一个包含所有支持的编码的 Accept-Encoding: 标头。

最后,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 库不会压缩/解压缩您的数据。 你必须自己做。

        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() );