python - 基本身份验证返回 401 客户端错误,但在邮递员中工作
问题描述
我已经浏览了许多与使用 Basic Auth 触发 GET 请求相关的类似帖子(例如:Python、HTTPS GET with basic authentication),但仍然无法解决问题。我不断收到错误requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url
使用相同的凭据,标题在邮递员中尝试相同,它按预期工作。验证了 api_key 的 base64encoded 值,password 和 postman 中使用的值完全一样,所以我不认为它的编码或资源访问权限问题。
python -V
Python 3.6.4 :: Anaconda, Inc.
方法一
api_key = 'some_api_key'
password = 'some_password'
headers = {'accept': 'application/json'}
url = 'https://test.access.com/this/url'
api_key_password = "%s:%s" % (api_key, password)
b64_encoded = b64encode(bytes(api_key_password, 'utf-8')).decode("ascii")
headers['authorization'] = 'Basic %s' % b64_encoded
response = requests.get(url,
headers=headers)
if (response.ok):
json_data = json.loads(response.content)
print (json_data)
else:
print (response)
response.raise_for_status()
方法二
api_key = 'some_api_key'
password = 'some_password'
url = 'https://test.access.com/this/url'
headers = {
'accept': 'application/json',
}
response = requests.get(url, headers=headers, auth=(api_key, password))
print (response.ok)
if (response.ok):
json_data = json.loads(response.content)
print (json_data)
else:
print (response)
response.raise_for_status()
你能提供一些指示吗?
解决方案
我有一个类似的问题(尽管在 .NET Framework 中)。
就我而言,原因是我最后使用了没有正斜杠的 url,而 API 显然不支持它。
所以https://test.access.com/this/url
抛出 401 错误未经授权
但
https://test.access.com/this/url/
返回 200 确定。
推荐阅读
- python - Pyinstaller 输出文件根本不起作用
- java - 找不到 org.jetbrains.trove4j:trove4j:20160824
- powershell - Powershell - 每天分配一个变量
- python - 循环遍历二维列表中的列
- javascript - 当 contextIsolation 设置为 true 时,如何从 HTML 文件访问 require
- azure-data-factory - 数据流中的 CosmosDB 接收器不符合目标数据集架构
- vb.net - 过滤没有数据源的DatagridView
- vue.js - 已安装 Vue Native 但 npm start 不起作用得到错误
- c# - 在 ASP.NET Core 3.1 框架中使用 IDataProtectionProvider 时如何指定加密密钥?
- c++ - 我是否想使用 virtual destructor=default 来正确处理具有虚拟功能的类?