简体   繁体   中英

Python 2.2.3 HTTP Basic Authentication Implementation

I am trying to implement the HTTP Basic Authentication in Python 2.2.3. This is code:

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)

I always get the URL Error 401. This code works perfectly in Python 3.4. Unfortunately I need to get this running in Python 2.2.3. Can someone please tell where am I going wrong ?

It worked after changing the code:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM