【问题标题】:what's the difference between requests.post and this straight curl?requests.post 和这个直卷曲有什么区别?
【发布时间】:2018-04-05 05:07:58
【问题描述】:

将 python 3.6.2 与 requests 库一起使用。

我正在尝试在战网 API 上使用 oauth2 进行身份验证,在第二个请求(用于令牌检索的请求)中,我收到了 400 错误,没有任何有用的解释(“内部服务器错误”)。 战网论坛上有人建议尝试使用curl 尝试相同的POST,并且它有效。 (这是我的论坛帖子:https://us.battle.net/forums/en/bnet/topic/20762236765)

我多次检查两者之间的一些愚蠢差异(可能是错字),但没有(我还通过复制粘贴从 curl 写回请求,得到相同的错误)。所以我想这两者之间应该有一些实际的行为差异。

这是python代码:

data = {
         'code': code,
         'redirect_uri': 'https%3A%2F%2Flocalhost%2Foauth2callback',
         'grant_type': 'authorization_code',
         'client_id': CLIENT_ID,
         'client_secret': CLIENT_SECRET,
         'scope': 'sc2.profile'
    }
resp = requests.post('https://eu.battle.net/oauth/token', data=data)

这是卷曲:

curl -X POST -s "https://eu.battle.net/oauth/token" \
    -d client_id='<same as above>' \
    -d client_secret='<same as above>'  \
    -d grant_type='authorization_code' \
    -d redirect_uri='https%3A%2F%2Flocalhost%2Foauth2callback' \
    -d scope='sc2.profile'  \
    -d code='<same as above>'

正如我所说,我想应该有一些不同的东西,但我不是 http 专家。标题中可能有什么?如何将请求设置为具有相同的行为?

【问题讨论】:

    标签: python http python-requests battlenet-api


    【解决方案1】:

    您不需要手动编码redirect_uri; requests 会为你做这件事。

    data = {
         'code': code,
         'redirect_uri': 'https://localhost/oauth2callback',
         'grant_type': 'authorization_code',
         'client_id': CLIENT_ID,
         'client_secret': CLIENT_SECRET,
         'scope': 'sc2.profile'
    }
    resp = requests.post('https://eu.battle.net/oauth/token', data=data)
    

    等效的curl 调用将使用--data-urlencode 而不是-d/--data。

    curl -X POST -s "https://eu.battle.net/oauth/token" \
        -d client_id='<same as above>' \
        -d client_secret='<same as above>'  \
        -d grant_type='authorization_code' \
        --data-urlencode redirect_uri='https://localhost/Foauth2callback' \
        -d scope='sc2.profile'  \
        -d code='<same as above>'
    

    要调试这样的问题,你可以发帖到https://httpbin.org/post;响应将准确显示 POST 请求中发送了哪些数据。

    【讨论】:

    • 我已经尝试不对该 uri 进行编码,但我得到了同样的错误。今晚我会尝试 httpbin.org 并告诉你我找到了什么
    • 您没有显示的三个值可能存在问题。
    • 好吧对不起,可能昨晚我累了,我在编码/解码方面犯了一些错误。实际上那是问题所在,谢谢。
    猜你喜欢
    • 2022-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多