Python请求POST - 错误400

时间:2018-06-06 07:36:53

标签: python python-requests

我有这段代码:

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())

我正在尝试测试连接到测试环境中的新auth服务(这就是为什么验证为FALSE)这应该给我访问令牌和令牌类型,并且我可以将它发送到API。

但我总是得到:

<Response [400]>  Bad Request   {u'error': u'invalid_request'}

我不确定是什么问题? 为什么这是一个糟糕的要求?

2 个答案:

答案 0 :(得分:2)

您似乎正在尝试使用client_credientials授权获取OAuth 2.0访问令牌。这是described in RFC6749

我在这里看到两个问题:

  • 您必须将字段发布为application/x-www-form-urlencoded而不是json。为此,请使用data而不是request.post()
  • 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())

答案 1 :(得分:0)

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

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)
相关问题