问题描述
我能够从登录 api 获取身份验证令牌,但我正在尝试使用它来查询事件 api,并且收到 401 客户端错误:url 错误消息未经授权。这是我的代码片段:
def action():
data = {
'login': 'xxxxxxxxx','password': 'xxxxx',}
urllib3.disable_warnings()
try:
timestamp = int(round(time.time() * 1000))
print(timestamp)
r = requests.post(
'https://host:port/www/core-service/rest/LoginService/login',data=data,verify=False)
login_request = untangle.parse(r.text)
user_session_id = login_request.ns3_loginResponse.ns3_return.cdata
print(user_session_id)
response = requests.post(
'https://host:port/detect-api/rest/v1/events/retrieve',headers={
"Accept": "application/json","Authorization": user_session_id,"Content-Type": "application/json"
},data={
"ids": 79745681,"startTime": timestamp,"endTime": timestamp
},verify=False)
print(response)
res = untangle.parse(response.text)
print(res)
有人可以指出我的代码有什么问题吗?
解决方法
您没有添加指向 API 的链接,所以我只是猜测可能会产生什么问题。
如果您设置了 "Content-Type": "application/json"
,则可能意味着您要发送 json
数据。
所以你应该使用
post(...,json=...)
代替
post(...,data=...).
使用 data=
将其作为 form
发送,而不是 json
。并且标题 Content-Type
无法更改。
当您使用 json=
时,您不必添加 "Content-Type": "application/json"
,因为 requests
会自动添加它。
编辑:
在评论中你说你有工作 curl
命令(但你没有说它有问题,你没有显示 curl
有问题)
在页面 https://curl.trillworks.com 上,您可以将 curl
转换为 Python
(以及少数其他语言),并且大多数情况下都可以正常工作。
顺便说一句:
如果您使用 postman 进行测试,那么它还有为 curl
、Python
和许多其他语言生成代码的功能。
您没有显示 API 文档的链接,但 API 文档通常包含 curl
的示例,有时甚至 Python
的示例。