Twitter REST API 1.1的问题 - 仅使用应用程序验证响应403使用Python时出错

时间:2013-04-04 11:50:09

标签: python twitter urllib2

我正在尝试通过POST请求连接到twiiter API作为docs say,但我总是得到403禁止错误。

这是我的代码。我在python 2.7中使用urlib2:

def auth_API():
    url = 'https://api.twitter.com/oauth2/token'
    header = {}
    values = {}
    header['User-Agent'] = 'Mozilla/6.0 (Windows NT 6.2; WOW64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1'
    header['Authorization'] = 'Basic ' + B64BEARERTOKENCREDS
    header['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    header['Accept-Encoding'] = 'gzip'
    values['grant_type'] = 'client_credentials'

    data = urllib.urlencode(values)
    req = urllib2.Request(url, data, header)
    try:
        response = urllib2.urlopen(req)
        response.read()
    except urllib2.HTTPError as e:
        print e

检查文档我发现了一个与我相同的示例请求:

Twitter示例:

POST /oauth2/token HTTP/1.1
Host: api.twitter.com
User-Agent: My Twitter App v1.0.23
Authorization: Basic NnB1[...]9JM29jYTNFOA==
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 29
Accept-Encoding: gzip

grant_type=client_credentials

我的要求:

POST /oauth2/token HTTP/1.1
Content-Length: 29
Accept-Encoding: gzip
Connection: close
User-Agent: Mozilla/6.0 (Windows NT 6.2; WOW64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1
Host: api.twitter.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Authorization: Basic NnB1[...]YTNFOA==

grant_type=client_credentials

对于这可能出错的任何想法?

问候。

PS:我知道有一些第三方库,但我想自己制作。

1 个答案:

答案 0 :(得分:2)

我解决了我的问题,错误是使用了base64.encodestring(),它在字符串末尾添加了一个\ n来搞乱请求。

使用base64.b64encode()代替工作正常。

此致