使用zlib解压缩Python请求响应

时间:2016-11-23 04:35:53

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

我尝试使用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; 
}

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

以下是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)