我在连接到 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] 删除。
我来说两句