如何在Python中发送HTTP标头请求而不是HTTP URL

时间:2010-02-04 12:00:16

标签: python django http oauth header

我正在做Oauth,而Linkedin需要我发送“标题”请求而不是URL请求(我不知道这意味着什么)。

这是有人在Google上说的话:

  

如果您使用的库不是   使用HTTP标头   授权,你不会   能够访问受保护的资源。   大多数OAuth库都有一个选项   您可以指定强制执行   它使用基于头的   授权。

无论如何,我将它指定为标题!我知道如何将其更改为标题。唯一的问题是......我不知道如何使用header方法请求

之前,没有标题方法:

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'

2 个答案:

答案 0 :(得分: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)

希望它有所帮助!

答案 1 :(得分:0)

您的connection.request方法可以接收HTTP标头:

connection.request(method,url,body = body,headers = {'Authorization':header})

对于OAuth,“标题”有一堆字段:

  

OAuth realm =“http://api.linkedin.com”,oauth_consumer_key =“##########”,oauth_nonce =“############”, oauth_signature =“########”,oauth_signature_method =“HMAC-SHA1”,oauth_timestamp =“#########”,oauth_token =“#########”,oauth_version = “1.0”

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