2010-08-26 100 views
1

我试图连接到radian6 api,这需要auth_appkey,auth_user和auth_pass作为md5加密。使用API​​密钥进行Urllib2身份验证

当我尝试使用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: [email protected] 
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 = '[email protected]' 
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加密密码,这就是我未被授权的原因?
你的智慧将非常感激,以挽救我的一天。

+0

那么,我已经解决了我自己的奥秘。我所要做的就是将所有授权标头设置为 req.add_header('auth_appkey',API_KEY) req.add_header('auth_user',USER) req.add_header('auth_pass',PASSWORD) 谢谢。 – mmrs151 2010-08-27 10:46:58

回答

1

在您的telnet会话中,您没有设置Authorization:标题,但这就是HTTPBasicAuthHandler使用的标题。 (你可以使用wireshark或类似的方法来听这个)。据推测,API不使用HTTP基本认证,而是使用家庭冲突变体。您可能想要删除该行并手动设置HTTP标头。

+0

是的,我已经使用 req.add_header( 'auth_appkey',API_KEY) req.add_header( 'AUTH_USER',USER) req.add_header( 'AUTH_PASS',PASSWORD) ,使其设置所有这三个头工作。 – mmrs151 2010-08-27 10:46:08

相关问题