python urllib2 basic authentication

≡放荡痞女 提交于 2020-01-21 07:14:48

问题


Hi i'm trying to use python to access an API URL using urllib2:

import urllib2

url = 'https://XXXXXXXXXX.com/'
username = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
password = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
pagehandle = urllib2.urlopen(url)

I don't know what the realm is but am assuming I can use default i.e. None.

Anyway, i am still get 401 error:

Traceback (most recent call last): File "test5.py", line 12, in pagehandle = urllib2.urlopen(url) File "/usr/lib/python2.6/urllib2.py", line 126, in urlopen return _opener.open(url, data, timeout) File "/usr/lib/python2.6/urllib2.py", line 397, in open response = meth(req, response) File "/usr/lib/python2.6/urllib2.py", line 510, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python2.6/urllib2.py", line 435, in error return self._call_chain(*args) File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain result = func(*args) File "/usr/lib/python2.6/urllib2.py", line 518, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 401: Unauthorized

so it seems there is something wrong with the authentication. Is it most likely the use of realm = None?

Thanks!


回答1:


I could not figure out why this method did not work but I was successful in calling the API using this code:

base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')

request = urllib2.Request(url)

request.add_header("Authorization", "Basic %s" % base64string) 

result = urllib2.urlopen(request)
        data = result.read()


来源:https://stackoverflow.com/questions/18534552/python-urllib2-basic-authentication

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!