2017-03-01 177 views
-1

我连接到Web API时出现问题,因为我无法获取结果的正文。无法从python中的JSON 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' 

现在我不明白为什么,因为当我尝试用邮差的API是给我回体结果: enter image description here

如果您在我的结果和图片中看到状态,我们有不同的状态,但我不太明白为什么看到我是通行证唱相同的参数

+0

答案所述的问题实际上是在截屏你提供。邮差显示标题部分,但代码不使用任何自定义标题,并将相关的字典输入数据参数。我猜,对于GET请求,它会进入url。 – hamilyon

+0

嘿家伙,我可以问你为什么我对这个问题有负面评分吗?我试图改善我所有的问题,但我不明白为什么我对该问题有负面评分:S –

回答

1

因为由requests返回的响应对象确实没有名为body的属性,并且文档并不意味着它确实如此。

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

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

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

1

你的问题是,你给报头数据

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

+0

我做了此更改,但我仍然收到一个错误,这看起来有我的身份验证问题,但我真的不明白为什么,因为我现在传递的信息与Postman相同,并且标题而不是数据:S –

+0

问题已解决,是一个身份验证问题和标题。非常感谢 –