2017-03-01 81 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

問題已解決,是一個身份驗證問題和標題。非常感謝 –