用curl解压缩gzip数据 [英] decompression gzip data with curl

查看:292
本文介绍了用curl解压缩gzip数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我期望curl导致服务器发送压缩数据并对其进行解压缩.

I expected curl to cause the server to send compressed data AND to decompress it.

实际上,我在HTTP标头中看到数据已压缩(变体:Accept-Encoding 内容编码:gzip),但是curl不会为我解压缩它.

Actually i see in HTTP header that the data is compressed (Vary: Accept-Encoding Content-Encoding: gzip), but curl doesn't decompress it for me.

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

Is there an additional command I should use for this?

推荐答案

请注意,此选项已重命名为如文档所述:

设置HTTP请求中发送的Accept-Encoding:标头的内容,并在接收到Content-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:标头.

So it does decode (i.e decompress) the response. Three encoding are supported: "identity" (does nothing), "zlib" and "gzip". Alternatively you can pass an empty string which creates an Accept-Encoding: header containing all supported encodings.

最后, httpbin 便于测试,因为它包含一个返回gzip内容的专用端点.这是一个示例:

At last, httpbin is handy to test it out as it contains a dedicated endpoint that returns gzip content. Here's an example:

#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
...

然后在stdout上写一个JSON响应(因此已解压缩).

And a JSON response (thus decompressed) is written on stdout.

这篇关于用curl解压缩gzip数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆