使用Python requests请求Vertex AI Endpoint遇gzip解码错误,curl正常
解决Vertex AI Endpoint请求的ContentDecodingError问题
1. 如何修改requests的Accept-Encoding请求头
当然可以修改,有两种常用方式:
- 手动指定请求头覆盖默认值:构造请求时显式设置
Accept-Encoding,比如禁用压缩(用identity表示不压缩),示例代码:
import requests endpoint_url = "你的Vertex AI Endpoint地址" payload = {"your": "json_data"} # 替换为实际请求体 custom_headers = { "Content-Type": "application/json", "Accept-Encoding": "identity" # 告诉服务端不要返回压缩内容 } response = requests.post(endpoint_url, json=payload, headers=custom_headers) response.raise_for_status() print(response.json())
- 修改全局默认头(不推荐):如果所有请求都需要调整,可修改requests的默认头,但这种方式会影响所有请求,谨慎使用:
import requests from requests.utils import default_headers # 获取默认头并删除Accept-Encoding default_headers = default_headers() del default_headers["Accept-Encoding"] response = requests.post(endpoint_url, json=payload, headers=default_headers)
2. 原请求失败的原因分析
出现('Received response with content-encoding: gzip, but failed to decode it.', error('Error -3 while decompressing data: incorrect header check'))错误,核心原因是客户端和服务端的压缩协议不匹配:
- requests默认会发送
Accept-Encoding: gzip, deflate头,请求服务端返回压缩内容;而curl默认不会主动发送这个头,服务端因此返回明文响应,所以curl能正常执行。 - 当requests发送压缩请求头后,服务端可能存在两种异常情况:
- 服务端错误地标记响应为gzip压缩,但实际返回的是明文JSON,导致客户端解码失败。
- 服务端的压缩逻辑存在问题,生成的gzip数据包头部损坏或格式错误,无法被requests的自动解码逻辑识别。
- 你设置
stream=True后手动解码成功,说明原始响应内容本身是有效的(比如是明文),只是服务端的压缩响应头与实际内容不匹配,requests的自动解码流程被误导了。
3. 推荐的解决方案
- 首选方案:手动设置
Accept-Encoding: identity,让服务端直接返回明文响应,彻底规避解码问题,代码示例见第一部分。 - 备选方案(保留压缩):尝试指定单一压缩编码,比如只请求deflate:
custom_headers = { "Content-Type": "application/json", "Accept-Encoding": "deflate" }
- 手动处理响应:如果需要保留
stream=True的方式,可手动处理原始响应内容:
import requests import gzip import json response = requests.post(endpoint_url, json=payload, stream=True) response.raw.decode_content = False # 禁用自动解码 raw_content = response.raw.read() # 尝试gzip解码,失败则直接使用原始内容 try: decoded_content = gzip.decompress(raw_content) except Exception: decoded_content = raw_content result = json.loads(decoded_content) print(result)
内容的提问来源于stack exchange,提问作者swigganicks
相关产品推荐
相关产品推荐

