2013-10-05 174 views
1

我使用的API 試圖訪問Twitter的Twitter的OAuth我創建了一個應用程序,並檢查「允許此應用程序可用於登錄與Twitter」,然後我按照這些步驟:與蟒蛇

https://dev.twitter.com/docs/api/1/post/oauth/request_token 
https://dev.twitter.com/docs/auth/authorizing-request 
https://dev.twitter.com/docs/auth/creating-signature 

但我得到

urllib2.HTTPError: HTTP Error 401: Unauthorized 

,所以我一定是做了錯誤的或錯過的東西

有人能發現我的錯誤?

import urllib2 
import time 
import urllib 
import hashlib 
import hmac 
import base64 

def escape(s): 
    return urllib.quote(s, safe='~') 

consumer_key = 'yBsHl3G6MqXx9JpnoLoGbA' 
consumer_secret = 'JBk5oUDLSuNAXxdBHrDmoUFxemw7IJ1a2yWPmCydX7w' 
http_method = 'POST' 
base_url = 'https://api.twitter.com/oauth/request_token' 
oauth_token_secret = '' 

data={'oauth_callback':'http://localhost.de:8000/accounts/callback/twitter'} 

header = { 
    'oauth_consumer_key': consumer_key, 
    'oauth_timestamp': str(int(time.time())), 
    'oauth_nonce': hashlib.md5(str(time.clock())).hexdigest(), 
    'oauth_version': '1.0', 
    'oauth_signature_method': 'HMAC-SHA1' 
} 
header.update(data) 

paramstr = '' 
for k in sorted(header): 
    paramstr+=escape(k)+'='+escape(header[k])+'&' 
paramstr = paramstr[:-1] 
print paramstr 

sig_base_str = http_method.upper()+'&'+escape(base_url)+'&'+escape(paramstr) 
print sig_base_str 
key = escape(consumer_secret)+'&'+escape(oauth_token_secret) 
signature = base64.b64encode(hmac.new(key, sig_base_str, hashlib.sha1).digest()) 

header['oauth_signature'] = signature 
header_str = 'OAuth ' 
for k in sorted(header): 
    header_str+=escape(k)+'="'+escape(header[k])+'", ' 
header_str = header_str[:-2] 
print header_str 

req=urllib2.Request(base_url, data=urllib.urlencode(data)) 
req.add_header('Authorization', header_str) 
print urllib2.urlopen(req).read() 

我知道有這樣做的庫,但我想我自己寫的代碼,用於測試目的

+0

祕密被假設是一個祕密。 :) – Arpit

+0

它只是一個測試應用程序,所以沒關係;) – elbarto132

回答

2

我解決它自己。 Twitter的文檔不是100%正確的。 例如這裏

https://dev.twitter.com/docs/api/1/post/oauth/request_token 

他們說,授權頭應該是這樣的

OAuth oauth_nonce="K7ny27JTpKVsTgdyLdDfmQQWVLERj2zAK5BslRsqyw", oauth_callback="http%3A%2F%2Fmyapp.com%3A3005%2Ftwitter%2Fprocess_callback", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1300228849", oauth_consumer_key="OqEqJeafRSF11jBMStrZz", oauth_signature="Pc%2BMLdv028fxCErFyi8KXFM%2BddU%3D", oauth_version="1.0" 

,但這是錯誤的,你不應該添加oauth_callback="http%3A%2F%2Fmyapp.com%3A3005%2Ftwitter%2Fprocess_callback"的授權頭