我试图使用python请求访问API端点。除了使用cURL之外,我无法成功地发送请求正文。下面是成功的cURL命令:
curl --location --request POST '<api endpoint url>' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'obj={"login":"<email>","pword":"<password>"}'
使用像这样的python请求会从API返回一个错误,因为请求的主体是:
payload = 'obj={"login":"<email>","pword":"<password>"}'
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.post(url, headers=headers, data=payload)
print(response.text)
我也尝试了requests.request("POST")
,但得到了同样的结果。
发布于 2022-03-31 20:00:37
您的数据是URL编码的,正如您在curl
内容类型标头中看到的那样,所以您必须以URL编码格式而不是JSON格式提供数据。
请使用下面的选项。requests
将自动将内容类型标头设置为application/x-www-form-urlencoded
。它还将负责URL编码。
data = {"login": "<email>", "pword": "<password>"}
response = requests.post(url, data=data)
https://stackoverflow.com/questions/71698390
复制相似问题