HTTP基本身份验证在python 3.4中不起作用 [英] HTTP basic authentication not working in python 3.4
本文介绍了HTTP基本身份验证在python 3.4中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用HTTP基本身份验证登录REST API,但无法正常工作并给出错误消息
I am trying to login to a REST API using HTTP Basic Authentication but it is not working and giving the error
HTTP error 400: Bad Request
这是我的代码:
import urllib.parse
import urllib.request
import urllib.response
# create an authorization handler
#auth_handler = urllib.request.HTTPPasswordMgrWithDefaultRealm()
auth_handler = urllib.request.HTTPBasicAuthHandler()
# Add the username and password.
# If we knew the realm, we could use it instead of None.
userName = "username"
passWord = "pass"
top_level_url = "http URL"
auth_handler.add_password(None, top_level_url, userName,passWord)
# create "opener" (OpenerDirector instance)
opener = urllib.request.build_opener(auth_handler)
# Install the opener.
# Now all calls to urllib.request.urlopen use our opener.
urllib.request.install_opener(opener)
# use the opener to fetch a URL
try:
result = opener.open(top_level_url)
#result = urllib.request.urlopen(top_level_url)
messages = result.read()
print (messages)
except IOError as e:
print (e)
推荐答案
以下python3代码将起作用:
The following python3 code will work:
import urllib.request
import base64
req = urllib.request.Request(download_url)
credentials = ('%s:%s' % (username, password))
encoded_credentials = base64.b64encode(credentials.encode('ascii'))
req.add_header('Authorization', 'Basic %s' % encoded_credentials.decode("ascii"))
with urllib.request.urlopen(req) as response, open(out_file_path, 'wb') as
out_file:
data = response.read()
out_file.write(data)
这篇关于HTTP基本身份验证在python 3.4中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文