标签:python http协议 base64 认证 basic
一、HTTP的Basic认证:1. 客户端向服务器请求数据,请求的内容可能是一个网页或者是一个其它的MIME类型,此时,假设客户端尚未被验证,则客户端提供如下请求至服务器:
Get/index.html HTTP/1.0 Host:www.baidu.com
2. 服务器向客户端发送验证请求代码401,服务器返回的数据大抵如下:
HTTP/1.0 401 Unauthorised Server: SokEvo/1.0 WWW-Authenticate: Basic realm="google.com" Content-Type: text/html Content-Length: xxx
Get /index.html HTTP/1.0 Host:www.google.com Authorization: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxx
import urllib2 from base64 import encodestring url = 'http://XXX.XXX.X.XX' user = 'a' passwd = 'aa' req = urllib2.Request(url) basestr = encodestring('%s:%s' % (user,passwd))[:-1] req.add_header('Authorization','Basic %s' % basestr) f = urllib2.urlopen(req)
import urllib2 url = 'http://XXX.XXX.X.XX' user = 'a' passwd = 'aa' hdlr = urllib2.HTTPBasicAuthHandler() hdlr.add_password('hello',url,user,passwd) ##此处需添入realm opener = urllib2.build_opener(hdlr) urllib2.install_opener(opener) f = urllib2.urlopen(url) 为了更通用我们来用HTTPPasswordMgrWithDefaultRealm密码管理器来实现: import urllib2 url = 'http://XXX.XXX.X.XX' user = 'a' passwd = 'aa' psmg = urllib2.HTTPPasswordMgrWithDefaultRealm() psmg.add_password(None,url,user,passwd) hdlr = urllib2.HTTPBasicAuthHandler(psmg) opener = urllib2.build_opener(hdlr) urllib2.install_opener(opener) f = urllib2.urlopen(url)
http://blog.itpub.net/23071790/viewspace-709367/
标签:python http协议 base64 认证 basic
原文地址:http://blog.csdn.net/ling1510/article/details/40515507