Twitter REST API 1.1的问题 - 仅适用于应用程序验证的响应403 Python错误
问题描述:
我试图通过POST请求连接到twiiter API作为docs say,但我总是得到403禁止的错误。Twitter REST API 1.1的问题 - 仅适用于应用程序验证的响应403 Python错误
这是我的代码。我使用urlib2在Python 2.7:
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:我知道这里有一些第三方库,但我想自己做。
答
我解决了我的问题,错误是在base64.encodestring()中添加了一个\ n在字符串的末尾搞乱了请求。
使用base64.b64encode()可以正常工作。
Regards