1

我正在尝试按照本指南在我的网络应用程序中使用 Youtube api https://developers.google.com/youtube/2.0/developers_guide_protocol_oauth2#OAuth2_Server_Side_Web_Applications_Flow我已经成功完成了第 3 步并获得了**授权码** .

现在我坚持向这个网址发出 POST 请求https://accounts.google.com/o/oauth2/token

我想提出这样的请求:(取自我上面给出的链接)

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

code=4/ux5gNj-_mIu4DOD_gNZdjX9EtOFf&
client_id=1084945748469-eg34imk572gdhu83gj5p0an9fut6urp5.apps.googleusercontent.com&
client_secret=hDBmMRhz7eJRsM9Z2q1oFBSe&
redirect_uri=http://localhost/oauth2callback&
grant_type=authorization_code

我试过这样的事情:

headers = {'Content-Type': 'application/x-www-form-urlencoded code=4/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&client_id=xxxxxxxxxxx.apps.googleusercontent.com&client_secret=xxxxxxxxxxxxxxxxx&redirect_uri=http://127.0.0.1:8000/information/youtube/&grant_type=authorization_code'}

r = requests.post(url, headers)

我收到了这个错误:

<Response [411]>
u'<!DOCTYPE html>\n<html lang=en>\n  <meta charset=utf-8>\n  <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">\n  <title>Error 411 (Length Required)!!1</title>\n  <style>\n    *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}\n  </style>\n  <a href=//www.google.com/><img src=//www.google.com/images/errors/logo_sm.gif alt=Google></a>\n  <p><b>411.</b> <ins>That\u2019s an error.</ins>\n  <p>POST requests require a <code>Content-length</code> header.  <ins>That\u2019s all we know.</ins>\n'

我知道我对发布请求有误,我需要您指导如何使其发挥作用。

谢谢!

4

2 回答 2

6

不要将数据放在标题中。改用datakwarg.post()_ 由于 urlencoded POST 正文是默认值,因此也无需通过headers参数指定它。

data = {
    'code': '4/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'client_id': 'xxxxxxxxxxx.apps.googleusercontent.com',
    'client_secret': 'xxxxxxxxxxxxxxxxx',
    'redirect_uri': 'http://127.0.0.1:8000/information/youtube/'.
    'grant_type': 'authorization_code'
}
r = requests.post(url, data=data)

您可以通过requests-oauth扩展让请求处理 OAuth 身份验证,从而使此代码更好: https ://github.com/maraujop/requests-oauth#readme

然后,您可以在不手动处理 OAuth 参数的情况下执行您的请求。

于 2012-06-22T18:02:23.393 回答
3

您需要使用的data参数requests.post

文档应该有所帮助:http ://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests

于 2012-06-22T18:02:15.213 回答