Skip to main content
 首页 » 编程设计

Python之发出 POST 请求

2025年05月04日9webabcd

我正尝试按照本指南在我的网络应用程序中使用 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

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

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' 

我知道我的发帖请求有误,我需要您的指导以使其发挥作用。

谢谢!

请您参考如下方法:

不要将数据放在标题中。使用 data kwarg .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 参数。