gpt4 book ai didi

python - 使用 zlib 解压 Python 请求响应

转载 作者:行者123 更新时间:2023-12-05 06:41:19 24 4
gpt4 key购买 nike

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

最佳答案

根据 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

关于python - 使用 zlib 解压 Python 请求响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40756106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com