如何使用 python 的 urllib2 库仅请求一次而不是两次身份验证 url
通常,我们使用 python urllib2 库请求身份验证 url,用法如下 此页面< /a> 描述,但这会导致对服务器的两次请求,第一个请求响应为 401 错误,然后第二个请求是客户端将用户名/密码编码到身份验证标头中并再次请求。但是,如果您确实知道领域和(用户名,密码),则只能直接访问该 url 一次。我可以通过将身份验证信息编码到请求标头中来做到这一点,并且它只请求一次,但我不能使用 HTTPPasswordMgrWithDefaultRealm 和相关类来做到这一点。
仅请求一次代码:
导入urllib2,base64 url = 'http://xxxx' 用户名 = 'jpx' 密码='jpx123' b64str = base64.encodestring('%s:%s' % (用户名, 密码)) 请求 = urllib2.Request(url) auth = '基本 %s' % b64str req.add_header('授权', auth) 尝试: 开启器 = urllib2.urlopen(req) 除了 IOError,e: 打印字符串(e) 打印 opener.read()
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, 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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,这就是 urllib 的密码管理器的工作原理。它仅在从服务器接收到
401
后才发送身份验证信息。您可以对很多内容进行子类化并更改该行为,但像在示例中那样将信息编码到标头中似乎更容易。Yeah, that's how password manager from
urllib
works. It only sends auth information after receiving401
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.