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

使用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发送压缩请求头后,服务端可能存在两种异常情况:
    1. 服务端错误地标记响应为gzip压缩,但实际返回的是明文JSON,导致客户端解码失败。
    2. 服务端的压缩逻辑存在问题,生成的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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 06:12:09