Python requests调用Pixela POST接口返回unmarshal报错如何解决?
报错原因
该错误由Pixela服务端无法正常解析请求体导致:服务端要求接收JSON格式的请求参数,但你调用requests.post()时使用了data参数传参,该参数默认会把字典编码为表单格式(Content-Type为application/x-www-form-urlencoded),格式不匹配触发了解析异常。
修复方法
有两种可选修复方案,任选其一即可:
- 方案1(推荐):将
data参数替换为json参数,requests会自动完成字典到JSON的序列化,同时自动设置正确的请求头:
import requests as re url = 'https://pixe.la/v1/users' myobj = { "token":"tonybui", "username":"Tonybui2003", "agreeTermsOfService":"yes", "notMinor":"yes" } response = re.post(url, json = myobj) print(response.text)
- 方案2:手动序列化字典为JSON字符串,同时显式指定请求头的Content-Type:
import requests as re import json url = 'https://pixe.la/v1/users' myobj = { "token":"tonybui", "username":"Tonybui2003", "agreeTermsOfService":"yes", "notMinor":"yes" } headers = {"Content-Type": "application/json"} response = re.post(url, data = json.dumps(myobj), headers = headers) print(response.text)
内容的提问来源于stack exchange,提问作者PHI LONG BUI
相关产品推荐
相关产品推荐

