python urllib2 基本身份验证 [英] python urllib2 basic authentication

查看:30
本文介绍了python urllib2 基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 python 访问使用 urllib2 的 API URL:

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.

无论如何,我仍然收到 401 错误:

Anyway, i am still get 401 error:

回溯(最近一次调用最后一次):文件test5.py",第 12 行,在pagehandle = urllib2.urlopen(url) 文件/usr/lib/python2.6/urllib2.py",第 126 行,在 urlopen 中返回 _opener.open(url, data, timeout) 文件/usr/lib/python2.6/urllib2.py",第 397 行,处于打开状态response = meth(req, response) 文件/usr/lib/python2.6/urllib2.py",第 510 行,在 http_response'http', request, response, code, msg, hdrs) 文件/usr/lib/python2.6/urllib2.py",第 435 行,错误返回 self._call_chain(*args) 文件/usr/lib/python2.6/urllib2.py",第 369 行,在 _call_chainresult = func(*args) 文件/usr/lib/python2.6/urllib2.py",第 518 行,在 http_error_default 中引发 HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 401: Unauthorized

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

所以看起来身份验证有问题.最有可能使用realm = None吗?

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

谢谢!

推荐答案

我不明白为什么这个方法不起作用,但我成功地使用以下代码调用了 API:

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()

这篇关于python urllib2 基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆