You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法解码pycurl GET请求响应,求问题排查与解决

问题根源

你收到的响应是gzip压缩格式,直接解码自然会乱码或抛出UTF-8解码错误——开头的0x8b字节正是gzip压缩数据的标志性开头。

解决方法

方法1:让PycURL自动处理压缩

给PycURL设置ACCEPT_ENCODING选项,告知服务器你支持压缩格式,同时让PycURL自动完成解压:

import pycurl
import certifi
from io import BytesIO

c = pycurl.Curl()
c.setopt(c.URL, 'http://pycurl.io/')
buffer = BytesIO()
c.setopt(c.WRITEDATA, buffer)
c.setopt(c.CAINFO, certifi.where())

# 添加这一行:让PycURL接受并自动解压gzip/deflate压缩的响应
c.setopt(c.ACCEPT_ENCODING, '')

c.perform()
c.close()

body = buffer.getvalue()
print(body.decode('utf-8'))

方法2:手动解压(备用)

如果自动处理失效,可以先检查响应头的Content-Encoding,再手动解压:

import pycurl
import certifi
import gzip
from io import BytesIO

c = pycurl.Curl()
c.setopt(c.URL, 'http://pycurl.io/')
buffer = BytesIO()
c.setopt(c.WRITEDATA, buffer)
c.setopt(c.CAINFO, certifi.where())

# 捕获响应头
response_headers = {}
def header_function(header_line):
    header_line = header_line.decode('iso-8859-1')
    if ':' not in header_line:
        return
    name, value = header_line.split(':', 1)
    name = name.strip().lower()
    response_headers[name] = value.strip()

c.setopt(c.HEADERFUNCTION, header_function)

c.perform()
c.close()

body = buffer.getvalue()
# 判断是否是gzip压缩
if response_headers.get('content-encoding') == 'gzip':
    body = gzip.decompress(body)

print(body.decode('utf-8'))
为什么别人能正常运行?

大概率是对方的PycURL环境默认启用了压缩处理,或者服务器对不同请求的Accept-Encoding头返回了未压缩的内容。

内容的提问来源于stack exchange,提问作者Claytor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 05:52:37