使用 curl 解压缩 gzip 数据
decompression gzip data with curl
我在代码中添加了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() );
相关文章:
- 防止主数据类型C++的隐式转换
- 用于访问容器<T>数据成员的正确 API
- 嵌套在类中时无法设置成员数据
- 使用流处理接收到的数据
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 在cuda线程之间共享大量常量数据
- C++将文本文件中的数据读取到结构数组中
- 如何在C++中序列化结构数据
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 在c代码之间共享数据的最佳方式
- 链表,反向函数,数据结构
- 数据成员SFINAE的C++17测试:gcc vs clang
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 如何对点云数据进行排序
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- 使用 curl 解压缩 gzip 数据
- zlib和gzip生成不同的数据