【问题标题】:decompression gzip data with curl使用 curl 解压 gzip 数据
【发布时间】:2014-01-13 22:24:33
【问题描述】:

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

我预计 curl 会导致服务器发送压缩数据并对其进行解压缩。

实际上我在 HTTP 标头中看到数据被压缩(变化:Accept-Encoding Content-Encoding: gzip),但 curl 不会为我解压缩。

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

【问题讨论】:

    标签: c++ curl libcurl


    【解决方案1】:

    请注意,此选项已重命名为 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 响应(因此被解压缩)被写入标准输出。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 下载错误(正如前面的评论所解释的),上传正确(因为 HTTP 不压缩上传)。
      • 如果您使用 CURLOPT_HTTPHEADER 指定 Accept-Encoding 标头,libcurl 将不会进行任何压缩/解压缩。但是如果你使用 CURLOPT_ACCEPT_ENCODING libcurl 会为你做一切。见curl.haxx.se/libcurl/c/CURLOPT_ACCEPT_ENCODING.html
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-21
      • 2012-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多