how to request authentication url only once, not twice, with python's urllib2 library
usually, we request an authentication url with python urllib2 library, usage is as this page describe, but this will cause 2 request for server , the first one is responsed with a 401 error,开发者_JS百科 and then the second one is the client encodes username/passwd into authentication header and request again. But, if you do know the realm and the (username, passwd), you can directly access the url only once. I can do it by encode authentication info into request header and it does request only once, But I can not do this with HTTPPasswordMgrWithDefaultRealm and the related class.
only once request code:
import urllib2, base64 url = 'http://xxxx' username = 'jpx' passwd = 'jpx123' b64str = base64.encodestring('%s:%s' % (username, passwd)) req = urllib2.Request(url) auth = 'Basic %s' % b64str req.add_header('Authorization', auth) try: opener = urllib2.urlopen(req) except IOError, e: print str(e) print opener.read()
Yeah, that's how password manager from urllib
works. It only sends auth information after receiving 401
from the server. You could subclass lots of stuff and change that behavior, but it seems easier to just encode the information into the header yourself like you did in the example.
精彩评论