我是Python新手。我使用"请求"库发送post请求。我能够发送没有报头的post请求,但当给出报头时,我得到HTTP 400错误。
import requests
API_ENDPOINT = "https://reqres.in/api/users"
data = {"name": "Name1", "job": "job1"}
headers = {'Content-Type': 'application/json'}
# sending post request and saving response as response object
full_output = requests.post(url = API_ENDPOINT, headers=headers, data = data)
print("response status", full_output.status_code)
print("response", full_output.text)
输出:
response status 400
response <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Bad Request</pre>
</body>
</html>
如果我在代码
中传递空头,它就会工作headers = {}
不知道为什么不工作。请求你的帮助。谢谢。
您正在发送python字典,api期望json字符串,您需要将您的字典编码为json字符串。你可以选择其中一个:
full_output = requests.post(url = API_ENDPOINT, headers=headers, data = json.dumps(data))
full_output = requests.post(url = API_ENDPOINT, json = data)