如何在Python中发送HTTP头请求而非HTTP URL
我正在做Oauth认证,LinkedIn要求我发送一个“头部”请求,而不是用URL请求(我对这是什么意思完全不懂)。
在谷歌上,有人这样说:
如果你使用的库没有用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'
2 个回答
0
你的连接请求方法可以带上HTTP头信息:
connection.request(方法, 地址, 请求体 = body, 头信息={'授权':header})
对于OAuth来说,'header'里面有很多字段:
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"
所有的####都是你需要准备或生成的内容。
2
我对你使用的这个特定的oauth库不太了解,所以没法对此发表评论。
不过,
从错误信息中可以明显看出,
oauth_request.to_header()
返回的是一个字典,而不是httplib.py所期待的字符串。在http头中设置认证凭证的方法如下:
来自 这个问题
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)
希望这能帮到你!