从POST请求接收JSON响应

2024-04-23 17:32:42 发布

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

使用POST请求,我的目标是从JSON响应接收授权代码。然而,我得到的唯一响应是我连接到的网页的HTML,而不是所需的JSON响应。你知道吗

import requests
from base64 import b64encode


appAuth = b64encode(b"QT8txxxxxxxx:n76mxxxxxxxxx").decode("ascii")
headers = { 'Authorization' : 'Basic %s' %  appAuth  }
url = "http://demo.skubana.com?grant_type=authorization_code&redirect_uri=demo.skubana.com/appstore&code=LCqYHU&cid=Y29tcGFueUlkMTI0MDYw"

r = requests.post(url, headers=headers,json={})

print(r.status_code)
print(r.content)

Tags: 代码importcomjsonurl目标democode
1条回答
网友
1楼 · 发布于 2024-04-23 17:32:42

在我看来,supplied API documentation for Skubana的具体化程度低得惊人。你知道吗

你可能错过了这一部分:

  1. Add the request path: /oauth/token

公平地说,这并没有反映在他们的“示例URL”中:

Sample Url: https://blah.skubana.com?grant_type=authorization_code&redirect_uri=redirect.com/callback&code=ABCDE&cid=ABCD1234

当您更改URL以包含该路径时,我会收到401未经授权的响应:

>>> url = "http://demo.skubana.com/oauth/token?grant_type=authorization_code&redirect_uri=demo.skubana.com/appstore&code=LCqYHU&cid=Y29tcGFueUlkMTI0MDYw"
>>> r = requests.post(url, headers=headers)
>>> r.status_code
401

顺便说一下,这也涉及到从POST到GET的重定向。但我强烈怀疑有了正确的凭证(我没有)你会得到你的代币。你知道吗

当您发布到https://demo.skubana.com时,您将被重定向到同一个URL以发出GET请求,其中:

Location: https://demo.skubana.com/?grant_type=authorization_code&redirect_uri=demo.skubana.com/appstore&code=LCqYHU&cid=Y29tcGFueUlkMTI0MDYw

然后转到仪表板:

Location: /work/dashboard

最后进入登录页面:

Location: https://demo.skubana.com/login

所有这些都记录在r.history列表中:

>>> r.history
[<Response [302]>, <Response [302]>, <Response [302]>]

请注意,您不必设置json={},只需使用:

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

请求库可以为您处理Base64编码,因为这只是part of the Basic Authentication scheme,只需传入您的\u APP\u密钥和\u APP\u SECRET值作为用户名和密码

YOUR_APP_KEY = "QT8txxxxxxxx"
YOUR_APP_SECRET = "n76mxxxxxxxxx"

url = "http://demo.skubana.com/oauth/token"
parameters = {
    "grant_type": "authorization_code",
    "redirect_uri": "demo.skubana.com/appstore",
    "code": "LCqYHU",
    "cid": "Y29tcGFueUlkMTI0MDYw",
}

r = requests.post(url, params=parameters, auth=(YOUR_APP_KEY, YOUR_APP_SECRET))

最后,考虑到重定向和完全缺少POST参数,我强烈怀疑GET请求也能正常工作:

r = requests.get(url, params=parameters, auth=(YOUR_APP_KEY, YOUR_APP_SECRET))

这只是绕过POST->;GET重定向。你知道吗

通常,OAuth2请求这样的令牌会将参数发布到post body中,因此也请尝试:

r = requests.post(url, data=parameters, auth=(YOUR_APP_KEY, YOUR_APP_SECRET))

如果params=parameters选项不能获得您的令牌,仍然可以。你知道吗

相关问题 更多 >