2013-04-11 32 views
4

我想使用純應用程序認證來訪問Twitter 1.1搜索終端。爲了做到這一點,我試圖執行在這裏的Twitter API的文檔上給出的步驟 - https://dev.twitter.com/docs/auth/application-only-auth(滾動到「發出僅應用程序的請求」)使用Python在Twitter 1.1中發佈僅限應用程序的請求

我不能在步驟2中獲得「不記名令牌」當我運行下面的代碼,我收到「答覆:302找到」這是一個重定向到的位置:https://api.twitter.com/oauth2/token 理想的情況下應該是「200 OK」

import urllib 
import base64 
import httplib 

CONSUMER_KEY = 'my_key' 
CONSUMER_SECRET = 'my_secret' 

encoded_CONSUMER_KEY = urllib.quote(CONSUMER_KEY) 
encoded_CONSUMER_SECRET = urllib.quote(CONSUMER_SECRET) 

concat_consumer_url = encoded_CONSUMER_KEY + ":" + encoded_CONSUMER_SECRET 

host = 'api.twitter.com' 
url = '/oauth2/token' 
params = urllib.urlencode({'grant_type' : 'client_credentials'}) 
req = httplib.HTTP(host) 
req.putrequest("POST", url) 
req.putheader("Host", host) 
req.putheader("User-Agent", "My Twitter 1.1") 
req.putheader("Authorization", "Basic %s" % base64.b64encode(concat_consumer_url)) 
req.putheader("Content-Type" ,"application/x-www-form-urlencoded;charset=UTF-8") 
req.putheader("Content-Length", "29") 
req.putheader("Accept-Encoding", "gzip") 

req.endheaders() 
req.send(params) 

# get the response 
statuscode, statusmessage, header = req.getreply() 
print "Response: ", statuscode, statusmessage 
print "Headers: ", header 

我不希望使用任何Twitter的API包裝訪問此。

+0

'HTTP 302'是一個重定向。檢查'位置:'並重定向? – ch3ka 2013-04-11 19:12:59

+0

@ ch3ka位置正確。它顯示「位置:https://api.twitter.com/oauth2/token」 – 2013-04-11 19:23:54

+0

如果您按照重定向(在位置:字段中請求URL),會發生什麼情況?順便說一句,「302」的回覆不是一個錯誤,但像ch3ka說的重定向。 – CaptSolo 2013-04-11 19:47:09

回答

2

問題是必須使用HTTPS連接調用URL。請檢查修改後的代碼是否有效。

import urllib 
import base64 
import httplib 

CONSUMER_KEY = 'my_key' 
CONSUMER_SECRET = 'my_secret' 

encoded_CONSUMER_KEY = urllib.quote(CONSUMER_KEY) 
encoded_CONSUMER_SECRET = urllib.quote(CONSUMER_SECRET) 

concat_consumer_url = encoded_CONSUMER_KEY + ":" + encoded_CONSUMER_SECRET 

host = 'api.twitter.com' 
url = '/oauth2/token/' 
params = urllib.urlencode({'grant_type' : 'client_credentials'}) 
req = httplib.HTTPSConnection(host) 
req.putrequest("POST", url) 
req.putheader("Host", host) 
req.putheader("User-Agent", "My Twitter 1.1") 
req.putheader("Authorization", "Basic %s" % base64.b64encode(concat_consumer_url)) 
req.putheader("Content-Type" ,"application/x-www-form-urlencoded;charset=UTF-8") 
req.putheader("Content-Length", "29") 
req.putheader("Accept-Encoding", "gzip") 

req.endheaders() 
req.send(params) 

resp = req.getresponse() 
print resp.status, resp.reason 
相關問題