【发布时间】: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