【问题标题】:Decompress Python requests response with zlib使用 zlib 解压 Python 请求响应
【发布时间】:2017-04-06 23:15:48
【问题描述】:

我正在尝试使用 Python 请求和 zlib 解压缩来自 Web 请求的响应,但我无法正确解压缩响应内容。这是我的代码:

import requests
import zlib

URL = "http://" #omitted real url
r = requests.get(URL)
print r.content
data = zlib.decompress(r.content, lib.MAX_WBITS)
print data

但是,我在更改 wbits 参数时不断收到各种错误。

zlib.error: Error -3 while decompressing data: incorrect header check
zlib.error: Error -3 while decompressing data: invalid stored block lengths

我尝试了用于 deflate、zlip 和 gzip 的 wbits 参数,如此处所述zlib.error: Error -3 while decompressing: incorrect header check

但仍然无法通过这些错误。我正在 Python 中尝试这样做,我得到了这段使用 Objective-C 完成的代码,但我不知道 Objective-C

#import "GTMNSData+zlib.h"
+ (NSData*) uncompress: (NSData*) data
{
    Byte *bytes= (Byte*)[data bytes];
    NSInteger length=[data length];
    NSMutableData* retdata=[[NSMutableData alloc]   initWithCapacity:length*3.5];

    NSInteger bSize=0;
    NSInteger offSet=0;
    while (true) {
        offSet+=bSize;
        if (offSet>=length) {
            break;
        }
        bSize=bytes[offSet];
        bSize+=(bytes[offSet+1]<<8);
        bSize+=(bytes[offSet+2]<<16);
        bSize+=(bytes[offSet+3]<<24);
        offSet+=4;
        if ((bSize==0)||(bSize+offSet>length)) {
            LogError(@"Invalid");
            return data;
        }
        [retdata appendData:[NSData gtm_dataByInflatingBytes: bytes+offSet length:bSize]];
    }
    return retdata; 
}

【问题讨论】:

  • 内容不是一个单一的 zlib 流,而是一系列以 4 字节 little endian 长度为前缀的流。我可能会写一个解码器。
  • 我也遇到了同样的问题,很想知道您是否找到了解决方案...

标签: python python-2.7 python-requests zlib compression


【解决方案1】:

根据 Python 请求文档位于:

上面写着:

You can also access the response body as bytes, for non-text requests:

>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...

The gzip and deflate transfer-encodings are automatically decoded for you.

如果请求理解编码,那么它应该已经被解压缩了。

如果您需要访问原始数据以处理不同的解压缩机制,请使用r.raw

【讨论】:

    【解决方案2】:

    以下是未经测试的 Objective-C 代码翻译:

    import zlib
    import struct
    
    def uncompress(data):
        length = len(data)
        ret = []
        bSize = 0
        offSet = 0
        while True:
            offSet += bSize
            if offSet >= length:
                break
    
            bSize = struct.unpack("<i", data[offSet:offSet+4])
            offSet += 4
            if bSize == 0 or bSize + offSet > length:
               print "Invalid"
               return ''.join(ret)
            ret.append(zlib.decompress(data[offSet:offSet+bSize]))
    
       return ''.join(ret)
    

    【讨论】:

      猜你喜欢
      • 2013-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-21
      • 1970-01-01
      • 2017-04-20
      相关资源
      最近更新 更多