无法从 python 中的 JSON WEB API 请求中获取正文

卡罗 1585

我在连接到 Web API 时遇到问题,因为我无法获得结果的正文。

这是我的代码:

import json,requests
url =('URL')
data={"Content-Type":"application/x-wwwform-urlencoded", "Authorization":"Valid JWT Token"}
myResponse1 = requests.get(url,data=data)
print ("status_code:"+ str(myResponse1.status_code))
print ("******************")
print ("text:"+ str(myResponse1.text))
print ("******************")
print ("encoding:"+ str(myResponse1.encoding))
print ("******************")
print ("json:"+ str(myResponse1.json))
print ("******************")
print ("content:"+ str(myResponse1.content))
print ("******************")
print ("body:"+ str(myResponse1.body))

这个输出:

status_code:401
******************
text:
******************
encoding:None
******************
json:<bound method Response.json of <Response [401]>>
******************
content:b''
******************
Traceback (most recent call last):
  File "C:\Users\Carlo\Desktop\Web API\Log-In_API.py", line 28, in <module>
    print ("body:"+ str(myResponse1.body))
AttributeError: 'Response' object has no attribute 'body'

现在我不明白为什么,因为当我使用 Postman 尝试 API 时,它给了我一个正文结果: 在此处输入图片说明

如果你在我的结果和图片中看到状态,我们有不同的状态,但我真的不明白为什么看到我正在传递相同的参数

丹尼尔罗斯曼

因为requests确实返回的 Response 对象没有名为 的属性body,并且文档并未暗示它有。

当您打印myResponse1.content时,您已经访问了响应的内容myResponse1.text

注意,json是一个方法;如果你想要内容为json,你需要调用它:myResponse1.json().

另请注意,授权和内容类型是标题,而不是查询参数。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章