【问题标题】:python > requests module > post > headers not workingpython > 请求模块 > 发布 > 标头不起作用
【发布时间】:2021-09-14 14:11:36
【问题描述】:
为什么我会收到这样的回复?我试图在 Discord 上询问人们,但没有人能解释。
>>>import requests
>>>api_url = "my_url"
>>>headers = {"Content-type": "application/json"}
>>>res = requests.post(api_url, "text to post", headers=headers)
>>>res.json()
{'message': '400: Bad Request', 'code': 0}
【问题讨论】:
标签:
python
python-3.x
python-requests
python-requests-html
python-requests-json
【解决方案1】:
因为您已收到来自服务器的此响应:
{'message': '400: Bad Request', 'code': 0}
这表明您实际上已经到达了服务器端点,因此您可能只是没有包含服务器期望请求的所有数据。
请注意,文档指定“数据”应为“(可选)字典、元组列表、字节或要在请求正文中发送的类似文件的对象”,因此可能是事先对文本进行编码的最佳实践喜欢:
my_text = "some json encoded text"
requests.post(api_url, my_text.encode("ascii"), headers = headers)
仔细检查您发送的数据(尤其是拼写)是否与服务器对请求的要求相符。
【解决方案2】:
试试这个:
import requests
import json
api_url = "my_url"
body = {'xxx': 'text to post'}
headers = {"Content-type": "application/json"}
res = requests.post(api_url, data=json.dumps(body), headers=headers)
res.json()