2017-07-06 2 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(すべてOK)であれば、サーバは私が必要とするデータの文字列を送信します。問題はありません。私が書いたコードは問題ありません。 200レスポンス:

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

しかし、私もエラーをキャッチする必要があります。その場合、サーバーはJSONを返します。 、その応答では、この行で私のアプリがクラッシュし

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

:これはエラー(Iは、Firefoxのポスターの拡張機能を使用して、それを持っている)からの応答である

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

これがキャッチエラーです:

java.io.FileNotFoundException: [url] 

どのようにしてJSONをサーバーから読み取ることができますか?

答えて

1

エラーはconn.getInputStream()メソッドによって発生します。サーバが応答ステータスが200
ないときは、入力ストリームを取得するために400

使用conn.getErrorStream()以上の応答コードを返した場合HttpUrlConnectiongetInputStream()FileNotFoundException例外をスローすることが知られている、これを確認してください:

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

関連する問題