c++ - 使用 curl 解压 gzip 数据

标签 c++ curl libcurl

我在我的代码中添加了 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/

相关文章:

php - cURL 中的数据二进制参数

bash - 使用 bash 变量将多个 header 传递给 curl 命令

c - 无法使用 libcurl 读取数据

c++ - 使用 libcurl 和 C++ 将从 IMAP 服务器下载的电子邮件保存到文件中

c++ - 在 Linux for Windows 下与 mingw32 交叉编译时链接 libcurl

c++ - 尝试使用 cmake 交叉编译 qt 应用程序时出现链接问题

c++ - 如何使用 QFtp::list 和 QFtp::listInfo 检查目录是否存在

c++ - 找不到 Windows SDK 版本 7.0

c++ - 在迭代时为 void * 分配更多内存,然后添加该值

php - curl_errno 返回 0 而不是 6