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

Python3构造非硬编码POST请求出现认证失败错误该如何解决?

错误原因
  • 认证失败的直接原因是请求头Authorization字段未正确代入用户输入的token变量:当前代码写的是固定字符串'Bearer token)',既硬编码了无效的token值,还多了一个多余的右括号,服务端识别到无效凭证直接返回认证失败。
  • 载荷payload部分所有值都加了引号,变成了固定字符串,没有使用用户输入的对应变量值,提交的用户参数全部错误。
  • status变量赋值语法错误:代码中写的是status: input("Enter status: "),错把赋值等号写成了冒号,导致status变量没有被正确赋值。
  • 如果修改后仍报该错误,请确认你输入的access token本身有效,未过期且拥有对应接口的调用权限。
修正后的完整代码
import requests
import json
import pprint

url = 'https://gorest.co.in/public/v1/users'
token = input("Enter your access token: ")
name = input("Enter full name: ")
gender = input("Enter gender: ")
email = input("Enter email: ")
# 修正赋值语法,冒号改为等号
status = input("Enter status: ")

# 修正payload,变量去掉引号,使用用户输入的实际值
payload = json.dumps({
    'name': name,
    'gender': gender,
    'email': email,
    'status': status
})

# 修正Authorization字段,使用f字符串拼接实际token值,删除多余右括号
headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Authorization': f'Bearer {token}'
}

response = requests.request('POST', url, data=payload, headers=headers)
pprint.pprint(response.json())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 08:54:05