2015-08-18 24 views
1

我有一個web服務返回的,有時,狀態401 它配備了一個JSON的身體,是這樣的:URL連接:如何獲得身體狀態返回!= 200?

{"status": { "message" : "Access Denied", "status_code":"401"}} 

現在,這是我使用,使服務器的請求的代碼:

HttpURLConnection conn = null; 
try{ 
    URL url = new URL(/* url */); 
    conn = (HttpURLConnection)url.openConnection(); //this can give 401 
    JsonReader reader = new JsonReader(new InputStreamReader(conn.getInputStream())); 

    JsonObject response = gson.fromJson(reader, JsonObject.class); 
    //response handling 
}catch(IOException ex){ 
     System.out.println(conn.getResponseMessage()); //not working 
} 

當請求失敗時我想閱讀該json正文,但getResponseMessage只是給了我一個通用的「未經授權」...所以如何檢索該JSON?

+0

在響應狀態爲200的情況下,您正在使用的代碼在哪裏?我在任何地方都看不到。 –

+0

首先嚐試任何Web服務工具,如SOAPUI中的webservice url,並確定給定請求的響應 –

+0

添加代碼以處理狀態爲200的響應......問題不是響應,問題是顯然是java的事實。 net.URL無法在返回代碼!= 200時檢索響應主體 – Phate

回答

1

您可以撥打conn.getErrorStream()在非200響應的情況下:

HttpURLConnection conn = null; 
try { 
    URL url = new URL(/* url */); 
    conn = (HttpURLConnection)url.openConnection(); //this can give 401 
    JsonReader reader = new JsonReader(new InputStreamReader(conn.getInputStream())); 

    JsonObject response = gson.fromJson(reader, JsonObject.class); 
} catch(IOException ex) { 
    JsonReader reader = new JsonReader(new InputStreamReader(conn.getErrorStream())); 
    JsonObject response = gson.fromJson(reader, JsonObject.class); 
} 

否則通過堆棧溢出數據庫粗略搜索將帶來你this article,其中提到該解決方案。

相關問題