如何使用管api中的刷新令牌更新访问令牌?

时间:2015-02-27 13:17:29

标签: python post youtube-api

我试过这个来更新我的访问令牌

import urllib
endpoint='https://accounts.google.com/o/oauth2/token'
data={'client_id':'25********15-6*********************7f.apps.googleusercontent.com','client_secret':'4********Pj-K*****x4aM','refresh_token':'1/tP************************O_XclU','grant_type':'refresh_token'}
encodedData=urllib.urlencode(data)
from httplib2 import Http
h = Http()
resp, content = h.request(endpoint, "POST", encodedData)

但收到了错误消息

'{\n  "error" : "invalid_request",\n  "error_description" : "Required parameter is missing: grant_type"\n}'

2 个答案:

答案 0 :(得分:1)

您应该在请求中指定标题,如下所示:

resp, content = h.request(uri=endpoint,
                          method="POST", 
                          body=encodedData, 
                          headers={'Content-type': 'application/x-www-form-urlencoded'})

答案 1 :(得分:0)

old-refresh_token 是您拥有的刷新令牌

CLIENT_ID,CLIENT_SECRET是您可以在Google开发者控制台中找到的凭据

http = httplib2.Http()
TOKEN_URL = "https://accounts.google.com/o/oauth2/token"

headers = {'Content-Type': 'application/x-www-form-urlencoded'}
parameters = urllib.urlencode({'refresh_token': old-refresh_token, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'grant_type': 'refresh_token'})
resp, response_token = http.request(TOKEN_URL, method='POST', body=parameters, headers=headers)
token_data = json.loads(response_token)
access_token = token_data['access_token']

变量 access_token 现在保存您的访问令牌

尝试一下