2017-07-06 66 views
0

我需要在Android中獲取POST請求中的JSON響應。Android - 從POST請求中讀取JSON

這是我到目前爲止的代碼:

String data = null; 
    try { 
     data = URLEncoder.encode("Field1", "UTF-8") 
       + "=" + URLEncoder.encode(field1, "UTF-8"); 
     data += "&" + URLEncoder.encode("Field2", "UTF-8") + "=" 
        + URLEncoder.encode(field2, "UTF-8"); 
    } catch (UnsupportedEncodingException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

     String text = ""; 
     BufferedReader reader=null; 

     // Send data 
      try 
      { 

       // Defined URL where to send data 
       URL url = new URL(Constants.URL_EMAIL_LOGIN); 

      // Send POST data request 

      HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 
      conn.setRequestMethod("POST"); 
      conn.setDoOutput(true); 
      OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
      wr.write(data); 
      wr.flush(); 
      int number = conn.getResponseCode(); 

      // Get the server response 

      reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 

      // Read Server Response 
      while((line = reader.readLine()) != null) 
       { 
        // Append server response in string 
        sb.append(line + "\n"); 
       } 


       text = sb.toString(); 
      } 
      catch(Exception ex) 
      { 

      } 
      finally 
      { 
       try 
       { 

        reader.close(); 
       } 

       catch(Exception ex) {} 
      } 

如果ResponseCode是200(都可以),服務器發送了我需要的數據的字符串。沒有問題,我已經發布的代碼處理它沒有問題。 200響應:

"{\r\n \"user\": \"AAAA\",\r\n \"token\": \" \",\r\n \"email\": \"[email protected]\" \r\n}" 

但我也需要捕捉錯誤。在這種情況下,服務器返回一個JSON。這是一個錯誤的響應(我使用Firefox的海報擴展了它):

{"Message":"Field1 is not correct."} 

有了這種反應,在這條線我的應用程序崩潰:

reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 

這是抓住了錯誤:

java.io.FileNotFoundException: [url] 

有誰知道我可以從服務器讀取的JSON

回答

1

錯誤是由conn.getInputStream()方法造成的。 HttpUrlConnection被稱爲拋出FileNotFoundException異常上getInputStream()如果服務器返回一個響應代碼大於或等於400

使用conn.getErrorStream()得到輸入流時響應狀態不是200
檢查:

BufferedInputStream inputStream = null; 

int status = conn.getResponseCode(); 

if (status != HttpURLConnection.HTTP_OK) { 
    inputStream = conn.getErrorStream(); 
} else { 
    inputStream = conn.getInputStream(); 
} 

並使用它在您reader爲:

reader = new BufferedReader(new InputStreamReader(inputStream)); 
+0

謝謝!它按預期工作:D –

+0

@ O.D。我很高興它是有幫助的! – jayeshsolanki93