2010-02-04 155 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 “

所有####都是您需要拥有或生成的东西。