使用API密钥进行Urllib2认证
我正在尝试连接到 radian6 的接口,这个接口需要用到 auth_appkey、auth_user 和经过 md5 加密的 auth_pass。
当我使用 telnet 连接时,可以成功收到响应的 xml 数据。
telnet sandboxapi.radian6.com 80
Trying 142.166.170.31...
Connected to sandboxapi.radian6.com.
Escape character is '^]'.
GET /socialcloud/v1/auth/authenticate HTTP/1.1
host: sandboxapi.radian6.com
auth_appkey: 123456789
auth_user: xxx@xxx.com
auth_pass: 'md5encryptedpassword'
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Date: Thu, 26 Aug 2010 14:17:52 GMT
Content-Type: application/xml
Content-Length: 471
但是当我用下面的 Python 代码尝试同样的操作时,
import urllib
import urllib2
user = 'xxx@xxx.com'
password = 'md5encryptedpasswrod'
base_url = 'http://sandboxapi.radian6.com/'
api_key = '123456789'
pwman = urllib2.HTTPPasswordMgrWithDefaultRealm()
pwman.add_password(None, base_url, user, password)
auth_handler = urllib2.HTTPBasicAuthHandler(pwman)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
req = urllib2.Request('http://sandboxapi.radian6.com/socialcloud/v1/auth/authenticate')
req.add_header('auth_appkey', api_key)
xml = urllib2.urlopen(req).read()
却出现了以下错误信息,
Traceback (most recent call last):
File "connectapi.py", line 17, in <module>
xml = urllib2.urlopen(req).read()
File"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 397, in open
response = meth(req, response)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 510, in http_response
'http', request, response, code, msg, hdrs)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 435, in error
return self._call_chain(*args)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 369, in _call_chain
result = func(*args)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 518, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: Unauthorized
我不知道我缺少了什么。是 API 密钥还是 md5 加密的密码导致我没有权限呢?
如果你能提供一些建议,我将非常感激,这样我就能解决这个问题了。
1 个回答
1
在你的 telnet
会话中,你没有设置 Authorization:
这个头信息,但 HTTPBasicAuthHandler
正是用这个来进行身份验证的。(你可以用 wireshark
或类似的工具来监听这个过程。)可以推测这个API并不是使用标准的HTTP基本认证,而是它自己定制的版本。你可能需要去掉那一行代码,手动设置HTTP头信息。