Python请求后出错400

2024-09-29 17:10:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个代码:

import requests
import json 

data={"client_id" : "a", "client_secret" : "thisissecret", "grant_type" : "clientcredentials", "scope" : "PublicApi"}

url = 'http://MYURL/connect/token'
response = requests.post(url, json=data, verify=False)
print(response)
print response.reason
print(response.json())

我正在尝试在测试环境中测试与新身份验证服务的连接(这就是verify为FALSE的原因)这应该会给我访问令牌和令牌类型,并使用它们我可以发布到API。在

但我总是得到:

^{pr2}$

我不知道是什么问题? 为什么这是一个错误的请求?在


Tags: 代码importclientidjsonurldatasecret
2条回答

您似乎正在尝试使用客户端凭据授予获取OAuth 2.0访问令牌。这是described in RFC6749

我看到了两个问题:

  • 您必须将字段作为application/x-www-form-urlencoded而不是json发布。为此,请使用request.post()data参数,而不是json
  • grant_type值必须是client_credentials,而不是clientcredentials

它给出了:

import requests

data = {"client_id" : "a", "client_secret" : "thisissecret", 
        "grant_type" : "client_credentials", "scope" : "PublicApi"}

url = 'http://MYURL/connect/token'
response = requests.post(url, data=data, verify=False)
if response.ok:
    print(response.json())

也许你需要设置标题的内容类型?在

import requests
import json 

data={"client_id" : "a", "client_secret" : "thisissecret", "grant_type" : "clientcredentials", "scope" : "PublicApi"}
headers = {'content-type': 'application/json'}

url = 'http://MYURL/connect/token'
response = requests.post(url, json=data, verify=False, headers=headers)

相关问题 更多 >

    热门问题