python - HTTP 基本身份验证在 python 3.4 中不起作用

标签 python basic-authentication

我正在尝试使用 HTTP 基本身份验证登录到 REST API,但它不起作用并出现错误

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 代码将起作用:

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)

关于python - HTTP 基本身份验证在 python 3.4 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29708708/

相关文章:

python 正则表达式匹配大小写选项

python - 如何为点击处理的参数列表指定默认值?

python - python中的Imoverlay

python - 按二维索引对三维 numpy 数组进行排序

java - 在不修改应用程序的情况下从 Tomcat 中的 HttpServletRequest.getRemoteUser() 获取值

asp.net-core - ASP.NET Core 中的基本身份验证

python - 对于带有 Python 的 Selenium,我怎样才能让它按 CTRL、SHIFT、i?

security - 对于服务器到服务器的通信,OAuth 是否比 Basic Auth 更安​​全

java - 通过 HttpClient 连接 Tomcat 管理器

http - REST 服务器对授权的响应