gpt4 book ai didi

python urllib2 基本认证

转载 作者:太空狗 更新时间:2023-10-30 02:21:03 25 4
gpt4 key购买 nike

您好,我正在尝试使用 python 通过 urllib2 访问 API URL:

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)

我不知道领域是什么,但假设我可以使用默认值,即无。

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

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 吗?

谢谢!

最佳答案

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

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 基本认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18534552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com