Post 请求 python vs curl

Post requests in python vs curl

有人可以建议使用 python 调用下面的正确语法吗?

curl "https://sometest.api.token" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}"

我的尝试:

import requests
import json

credentials='1111'
secret='2222'

url = 'https://sometest.api.token'
body = {'client_credentials':credentials,'client_secret':secret}
headers = {'Content-type': 'application/x-www-form-urlencoded'}

r = requests.post(url, data=json.dumps(body), headers=headers)

由于documentation,如果你想发送一些表单编码的数据,你只需将字典传递给数据参数。

所以你必须尝试:

import requests
import json

credentials='1111'
secret='2222'

url = 'https://sometest.api.token'
body = {'client_credentials':credentials, 'client_secret':secret}
headers = {'Content-Type': 'application/x-www-form-urlencoded'}

r = requests.post(url, data=body, headers=headers)

而且你在python代码中的参数与curl中的参数不同,也许你需要检查一下。