2010-02-04 157 views
0

我在做Oauth,Linkedin需要我發送「標頭」請求而不是URL請求(我不知道這意味着什麼)。如何在Python中發送HTTP標頭請求而不是HTTP

這是有人說在谷歌:

如果您使用的是庫不 的 授權使用HTTP頭,你不會是 能夠訪問受保護的資源。 大多數OAuth庫都有一個選項 ,您可以指定它將強制 它使用基於標頭的 授權。

無論如何,我指定它爲標題!我知道如何將其更改爲標題。唯一的問題是...我不知道如何使用頭部方法請求東西。

之前,沒有頭的方法:

url = oauth_request.to_url() 
connection.request(oauth_request.http_method,url) 
response = connection.getresponse() 
s = response.read() 

現在:

url = oauth_request.to_header() 
connection.request(oauth_request.http_method,url) 
response = connection.getresponse() 
s = response.read() 

但是當我運行它,我得到這個奇怪的回溯。

File "/usr/lib/python2.6/httplib.py" in request 
    874.    self._send_request(method, url, body, headers) 
File "/usr/lib/python2.6/httplib.py" in _send_request 
    891.   self.putrequest(method, url, **skips) 
File "/usr/lib/python2.6/httplib.py" in putrequest 
    807.     if url.startswith('http'): 

Exception Type: AttributeError at /g/ 
Exception Value: 'dict' object has no attribute 'startswith' 
+0

我解決了它。我只是把第三個參數,這是頭。 – TIMEX 2010-02-04 12:40:41

回答

2

我不知道你使用的這個特定的oauth庫,所以我不能評論這個。

但是,

  • 它可以從追溯清楚地確定,即oauth_request.to_header()返回一個字典,而不是一個字符串,httplib.py預期。

  • 設置認證憑證在HTTP頭的方法如下:

this question

password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() 
top_level_url = "http://example.com/" 
password_mgr.add_password(None, top_level_url, 'user', 'password') 
handler = urllib2.HTTPBasicAuthHandler(password_mgr) 
opener = urllib2.build_opener(urllib2.HTTPHandler, handler) 
request = urllib2.Request(url) 

希望它能幫助!

0

你connection.request方法可以採取在HTTP頭中:

connection.request(方法,URL,身體=體,標題= { '授權':標題})

是OAuth,有一串字段的那個 '標題' 具有:

OAuth的境界= 「http://api.linkedin.com」,oauth_consumer_key = 「##########」,oauth_nonce =」 ############「,oauth_signature =」########「,oauth_signature_method =」HMAC-SHA1「,oauth_timestamp =」#########「,oauth_token =「#########」,oauth_version =「1.0 「

所有####都是您需要擁有或生成的東西。