【问题标题】:Can't get the body from a JSON WEB API request in python无法从 python 中的 JSON WEB API 请求中获取正文
【发布时间】:2017-03-01 12:42:38
【问题描述】:

当我连接到我的 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 时,会返回一个正文结果:

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

【问题讨论】:

  • 答案实际上在您提供的屏幕截图中。 Postman 显示 headers 部分,但代码不使用任何自定义 headers,并将相关 dict 提供给 data 参数。我猜,对于 GET 请求,哪个进入 url。
  • 大家好,请问为什么我在这个问题上得了负分?我正在努力改善我所有的问题,但我真的不明白为什么我在那个问题上得分为负:S

标签: python json python-3.x asp.net-web-api python-requests


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

    您的问题是您将标题作为数据提供

    data={"Content-Type":"application/x-wwwform-urlencoded", "Authorization":"Valid JWT Token"}
    myResponse1 = requests.get(url,data=data)
    

    您应该使用参数标题

        headers={"Content-Type":"application/x-wwwform-urlencoded", "Authorization":"Valid JWT Token"}
        myResponse1 = requests.get(url,headers=headers)
    

    还有Daniel描述的问题

    【讨论】:

    • 我做了这个改变,但我仍然得到一个错误,这看起来我有一个身份验证问题,但我真的不明白为什么,因为我现在传递的信息与 Postman 和使用标题而不是数据:S
    • 问题已解决,是身份验证问题加上标题。非常感谢
    猜你喜欢
    • 2017-10-19
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多