Python 2.2.3 HTTP基本认证实现

时间:2014-12-14 03:22:28

标签: python python-2.2

我正在尝试在Python 2.2.3中实现HTTP基本身份验证。这是代码:

import urllib2

proxyUserName1='<proxyusername>'
proxyPassword1='<proxypassword>'
realmName1='<realm>'
proxyUri1='<uri>'

passman=urllib2.HTTPPasswordMgr()
passman.add_password(realm=realmName1, uri=proxyUri1, user=proxyUserName1, passwd=proxyPassword1)
auth_handler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)

# Setting up the request & request parameters
login_url_request = urllib2.Request('<URL To be Accessed>')

# Getting the Response & reading it.
try:
    url_socket_connection = urllib2.urlopen(login_url_request)
except urllib2.URLError, urlerror:
    print ("URL Error Occured:")
    print (urlerror.code)
    print (urlerror.headers)
except urllib2.HTTPError, httperror:
    print ("HTTP Error Occured:")
    print (httperror.code)
    print (httperror.headers)
else:
    login_api_response = str(url_socket_connection.read())
    print (login_api_response)

我总是得到URL错误401.这段代码在Python 3.4中完美运行。不幸的是,我需要在Python 2.2.3中运行它。有人可以告诉我哪里出错了吗?

1 个答案:

答案 0 :(得分:0)

更改代码后它起作用了:

import urllib2
import base64

proxyUserName1='<proxyusername>'
proxyPassword1='<proxypassword>'
realmName1='<realm>'
proxyUri1='<uri>'
base64encodedstring = base64.encodestring('%s:%s' % (proxyUserName1, proxyPassword1)).replace('\n', '')

passman=urllib2.HTTPPasswordMgr()
passman.add_password(realm=realmName1, uri=proxyUri1, user=proxyUserName1, passwd=proxyPassword1)
auth_handler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)

# Setting up the request & request parameters
login_url_request = urllib2.Request('<URL To be Accessed>')
login_url_request.add_header('Authorization', 'Basic %s' % base64encodedstring)

# Getting the Response & reading it.
try:
    url_socket_connection = urllib2.urlopen(login_url_request)
except urllib2.URLError, urlerror:
    print ("URL Error Occured:")
    print (urlerror.code)
    print (urlerror.headers)
except urllib2.HTTPError, httperror:
    print ("HTTP Error Occured:")
    print (httperror.code)
    print (httperror.headers)
else:
    login_api_response = str(url_socket_connection.read())
    print (login_api_response)