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

Python解析POST请求返回JSON 提取access_token(Bearer令牌)

解决方案

requests 库原生支持JSON响应解析,不需要手动处理返回的字符串内容,调用响应对象的.json()方法就能把JSON格式的返回值转换为Python字典,直接通过键名即可提取目标字段。

代码修改方式

替换原代码中请求发送后的打印逻辑即可,调整后的相关代码片段如下:

endpoint2 = "[endpoint without the code]" + code
# 发送POST请求,若接口要求携带参数,记得把定义好的params传入,如requests.post(endpoint2, data=params)
token_endpoint = requests.post(endpoint2)

# 先校验请求状态,避免接口报错时解析异常
if token_endpoint.ok:
    resp_dict = token_endpoint.json()
    # 提取access_token为独立变量,供后续接口调用使用
    access_token = resp_dict["access_token"]
    # 按需提取其他字段
    refresh_token = resp_dict.get("refresh_token")
    expire_time = resp_dict.get("expires_in")
    
    print(f"成功获取令牌,有效期{expire_time}秒")
else:
    print(f"令牌请求失败,状态码:{token_endpoint.status_code},返回内容:{token_endpoint.text}")

补充说明

  • 不建议用字符串切片、正则匹配的方式从.text结果中提取字段,接口返回字段顺序、格式微调就会导致逻辑失效,.json()是官方提供的标准解析方案,稳定性更高。
  • 你当前代码中定义的params参数字典没有传入POST请求,如果令牌接口要求携带客户端ID、密钥等参数,需要按照接口要求把params作为data(表单传参)或json(JSON体传参)参数传入requests.post,否则接口可能会因为缺少参数返回错误。
  • 如果担心键不存在导致报错,可以用resp_dict.get("access_token")替代方括号取值,键不存在时会返回None而不是直接抛出异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 17:36:23