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

使用Python Requests提交JSON时遭遇HTTP 500错误求助

解决提交JSON数据时的500服务器错误

我一眼就看出问题所在了——你提交数据的方式不对,导致服务器无法正确解析JSON!

错误原因

你用data=val参数发送请求时,requests库会把你的字典自动编码成表单格式(application/x-www-form-urlencoded),但服务器期望的是纯JSON格式的请求体。这种格式不匹配让服务器在解析时触发了语法错误,也就是你看到的:

500 Internal Server Error {"code":"500","error":"invalid character 'o' in literal true (expecting 'r')","message"

两种修复方案

方案1:直接使用json参数(推荐)

requests库提供了更便捷的json参数,它会自动把字典转换成JSON字符串,同时设置正确的Content-Type: application/json请求头,一步到位:

import requests
val = {"token": "90467e25e2c5bbf6476310f9aeb1d005a73ecea5", "email": "jaycops@gmail.com", "answer": [{"NU_INSCRICAO": "160000000001", "NOTA_FINAL": 623.3}, {"NU_INSCRICAO": "160000000002", "NOTA_FINAL": 567.2}, {"NU_INSCRICAO": "160000000003", "NOTA_FINAL": 403.1} ]}
# 替换data为json参数
r = requests.post("https://api.codenation.com.br/v1/user/acceleration/data-science/challenge/enem-1/submit", json=val)
print(r.status_code, r.reason)
print(r.text)

方案2:手动转换JSON并设置请求头

如果你需要更精细地控制请求内容,可以手动把字典转成JSON字符串,再设置对应的请求头:

import requests
import json

val = {"token": "90467e25e2c5bbf6476310f9aeb1d005a73ecea5", "email": "jaycops@gmail.com", "answer": [{"NU_INSCRICAO": "160000000001", "NOTA_FINAL": 623.3}, {"NU_INSCRICAO": "160000000002", "NOTA_FINAL": 567.2}, {"NU_INSCRICAO": "160000000003", "NOTA_FINAL": 403.1} ]}
# 将字典转为JSON格式字符串
json_payload = json.dumps(val)
# 明确告诉服务器请求体是JSON格式
headers = {"Content-Type": "application/json"}
r = requests.post("https://api.codenation.com.br/v1/user/acceleration/data-science/challenge/enem-1/submit", data=json_payload, headers=headers)
print(r.status_code, r.reason)
print(r.text)

为什么原来的代码会报错?

当你使用data=val时,requests会把你的字典编码成类似这样的表单数据:

token=90467e25e2c5bbf6476310f9aeb1d005a73ecea5&email=jaycops%40gmail.com&answer=...

服务器收到这个后,尝试把它当作JSON解析,自然会出现语法错误——表单格式和JSON的语法规则完全不兼容,这就是那个"invalid character"错误的由来。

内容的提问来源于stack exchange,提问作者Joao Henrique Ferreira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:24:14