"令牌无效或过期"尝试访问Twitter API时出错

时间:2016-05-24 14:11:47

标签: python twitter oauth twitter-oauth

我尝试使用Application-only authorization来访问Twitter API。我可以正确获得一个Bearer令牌(至少我是这么认为的!)但是当我尝试使用令牌进行API调用时,我总是会遇到Invalid or expired token错误。

twitter_consumer_key = b"<MY_APP_CONSUMER_KEY>"
twitter_consumer_secret = b"<MY_APP_SECRET_KEY>"
twitter_keys = base64.standard_b64encode(twitter_consumer_key + b':' + twitter_consumer_secret)

content = {'grant_type': 'client_credentials'}
post_headers = {
    b'Authorization': b'Basic ' + twitter_keys,
    b'Content-Type': b'application/x-www-form-urlencoded;charset=UTF-8'
}

twitter_bearer = requests.post('https://api.twitter.com/oauth2/token', headers=post_headers, data=content).json()['access_token']
twitter_headers = {
    b'Authorization': b'Bearer ' + base64.b64encode(twitter_bearer.encode('utf-8')),
}
response = requests.get("https://api.twitter.com/1.1/users/show.json?screen_name=itechbrij",
                                 headers=twitter_headers).text

print(twitter_followers)提供{"errors":[{"code":89,"message":"Invalid or expired token."}]}

感谢任何帮助。感谢

1 个答案:

答案 0 :(得分:0)

BOLD

中尝试这些更改

twitter_keys = base64.standard_b64encode((twitter_consumer_key +&#39;:&#39; + twitter_consumer_secret) .encode(&#39; utf8&#39;)

post_headers = {     &#39;用户代理&#39;:&#39;您的用户代理字符串     &#39;授权&#39;:&#39;基本&#39; + twitter_keys **。decode(&#39; utf8&#39;)**,     &#39;内容类型&#39;:&#39; application / x-www-form-urlencoded; charset = UTF-8&#39; }

twitter_bearer = requests.post(     &#39; $scope.$digest(); documentation&#39 ;,     标题= post_headers,     的 PARAMS =内容)上传.json()[&#39;的access_token&#39;]