当cURL工作时,Python请求库不工作 [英] Python requests library is not working, while cURL is working
问题描述
我需要使用Python从Microsoft API检索JWT(JSON Web令牌)(请检查
I need to retrieve a JWT (JSON Web Token) from a Microsoft API using Python (check this API documentation for Microsoft Graph)
使用requests
库的以下Python代码无法使用HTTP响应代码400,但是,等效的cURL命令也可以使用以返回包含JWT的JSON.
The following Python code using the requests
library does not work giving HTTP response code 400, however, the equivalent cURL command does work giving back the expected JSON containing the JWT.
Python/requests
代码:
Python / requests
code:
tenant = "<MY_FOO_TENANT>"
token_url = "https://login.microsoftonline.com/{}/oauth2/v2.0/token".format(tenant)
http_headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
http_query_params = {
"client_id": "<MY_FOO_C_ID>",
"scope": "<MY_FOO_SCOPE>",
"client_secret": "<MY_FOO_C_SECRET>",
"grant_type": "client_credentials",
}
http_response = requests.post(token_url, params=http_query_params, headers=http_headers)
cURL命令:
curl -v -X POST \
--data-urlencode 'client_id=<MY_FOO_C_ID>' \
--data-urlencode 'scope=<MY_FOO_SCOPE>' \
--data-urlencode 'client_secret=<MY_FOO_C_SECRET>' \
--data-urlencode 'grant_type=client_credentials' \
-H 'Content-Type: application/x-www-form-urlencoded' \
'https://login.microsoftonline.com/<MY_FOO_TENANT>/oauth2/v2.0/token'
从requests
库的详细输出中,我可以看到它是对所有这些HTTP查询参数进行URL编码的,所以我倾向于认为这不是问题.
From the verbose output of the requests
library I can see that it is URL encoding all those HTTP query parameters, so I tend to think that should not be the problem.
- Python实现有什么问题?
- 如何使其工作?
推荐答案
,您应将http_query_params
作为data
而不是params
传递.尝试以下代码:
you should pass http_query_params
as data
instead of params
. try the following code:
tenant = "<MY_FOO_TENANT>"
token_url = "https://login.microsoftonline.com/{}/oauth2/v2.0/token".format(tenant)
http_headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
http_body = {
"client_id": "<MY_FOO_C_ID>",
"scope": "<MY_FOO_SCOPE>",
"client_secret": "<MY_FOO_C_SECRET>",
"grant_type": "client_credentials",
}
http_response = requests.post(token_url, data=http_body, headers=http_headers)
希望这会有所帮助
这篇关于当cURL工作时,Python请求库不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!