我正在尝试使用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")
,但得到了相同的结果。
您的数据是URL编码的,正如您在curl
Content-Type标头中看到的那样,因此您必须以URL编码的格式而不是JSON提供数据。
请使用以下内容。requests
将自动将"内容类型"标头设置为application/x-www-form-urlencoded
。它还将处理URL编码。
data = {"login": "<email>", "pword": "<password>"}
response = requests.post(url, data=data)