当您未获得授权并返回401状态时,将引发urllib2.HTTPError异常:>>> import urllib2, base64
>>> req = urllib2.Request('http://httpbin.org/basic-auth/foouser/barpw')
>>> base64string = base64.encodestring("%s:%s" % ("username", "password")).replace("\n", "")
>>> req.add_header("Authorization", "Basic %s" % base64string)
>>> urllib2.urlopen(req)
Traceback (most recent call last):
File "", line 1, in
File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 410, in open
response = meth(req, response)
File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 448, in error
return self._call_chain(*args)
File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: UNAUTHORIZED
成功授权后,您将得到一个响应对象:
^{pr2}$