简体   繁体   English

为什么这个 curl 命令有效,但我通过 python 发出的请求无效?

[英]Why does this curl command work but not my post request via python?

I'm trying to make a POST request to https://accounts.spotify.com/api/token via python and the request, library but can't get it to work.我正在尝试通过 python 和请求库向https: //accounts.spotify.com/api/token 发出 POST 请求,但无法使其正常工作。 I'm able to execute the request via curl command:我可以通过 curl 命令执行请求:

note - params enclosed in * * are correct and work in the curl request注意 - 包含在 * * 中的参数是正确的,并且在 curl 请求中有效

 curl -H "Authorization: Basic *base 64 encoded client ID and secret*"
 -d grant_type=authorization_code -d code=*auth code* -d 
 redirect_uri=https%3A%2F%2Fopen.spotify.com%2F 
 https://accounts.spotify.com/api/token 

and the request works just fine, however when I try to make what I think is the exact same request in python, I always get the same bad request error并且请求工作得很好,但是当我尝试在 python 中提出我认为完全相同的请求时,我总是得到相同的错误请求错误

    headers = {
        "Authorization": "Basic *base64 encoded client ID and secret*"
    }
    params = {
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": "https://open.spotify.com/"
    }

    response = requests.post(
        url,
        params=params,
        headers=headers
    )

If you can help me figure out how the two requests differ and why the python one never seems to work that would be amazing.如果你能帮我弄清楚这两个请求有何不同,以及为什么 python 似乎永远无法工作,那将是惊人的。

see section 2. of https://developer.spotify.com/documentation/general/guides/authorization-guide/ for the params有关参数,请参见https://developer.spotify.com/documentation/general/guides/authorization-guide/的第 2 节

You use -d flag in your curl request which stands for data .您在代表datacurl请求中使用-d标志。

So you should pass your params as data also in your Python POST request:因此,您还应该在 Python POST请求中将参数作为data传递:

headers = {
        "Authorization": "Basic *base64 encoded client ID and secret*"
    }
    params = {
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": "https://open.spotify.com/"
    }

    response = requests.post(
        url,
        data=params,
        headers=headers
    )

seems like you put payload under wrong argument, try to change params into json or data (depends on what type of requests that API accept):似乎您将有效负载置于错误的参数下,尝试将params更改为jsondata (取决于 API 接受的请求类型):

response = requests.post(
    url,
    json=params,
    headers=headers
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM