我尝试通过Python请求模块与Google API通信requests module 。 接收授权码工作正常。然后我尝试使用以下代码获取访问 token :
params = {
'code': gauth,
'client_id': 'myid',
'client_secret': 'mysecret',
'redirect_uri': 'http://localhost:5000/googleauth',
'grant_type': 'authorization_code'
}
headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
r = requests.post('http://accounts.google.com/o/oauth2/token', data=params)
“gauth”保存从 API 收到的授权代码。 我面临的问题是 API 回复“405 Method Not allowed”。
我仔细检查了一下,它确实是作为 POST 请求发送的。当我使用诸如 Postman 之类的工具时,它工作正常。手动触发请求。
为了测试,我在应用程序中创建了一个虚拟页面,用于显示 POST 请求的正文内容。 在那里我意识到,当我通过 Python 请求发送请求时,redirect_uri 是经过 urlencoded 的(如 python-interpreter 中所示),但当我使用 Postman 时则不是(如 Postman chrome 选项卡中所示)。这可能是问题的原因吗?或者这更有可能只是一个显示问题(例如,Postman 解码 urlencoded 字符串)?
据我所知,不可能在请求中停用 urlencoding,因此我无法对此进行测试。
非常感谢任何提示:)
最佳答案
又过了一个小时,我明白了:
该请求必须发送至 https://accounts.google.com/o/oauth2/token
(httpS,而不是 http)。
如果请求发送到 http://,它会被重定向到 https,在此过程中,POST 会变成 GET,因此会出现错误消息。
关于python - Google Oauth Python 请求 : Method Not Allowed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20307815/