O.D.
O.D.

Reputation: 57

Android - Read JSON from POST request

I need to catch the JSON response from a POST request in Android.

This is my code so far:

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) {}
          }

If the ResponseCode is 200 (all OK), the server sends me a string with the data I need. No problem with that, the code I have posted deals with it with no problem. A 200 response:

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

But I also need to catch the errors. In that case, the server returns a JSON. This is the response from an error (I have got it using the Poster extension of Firefox):

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

With that response, my app crashes in this line:

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

This is the caught error:

java.io.FileNotFoundException: [url]

Does anyone know how can I read the JSON from the server?

Upvotes: 0

Views: 861

Answers (1)

jayeshsolanki93
jayeshsolanki93

Reputation: 2136

The error is caused by the conn.getInputStream() method. HttpUrlConnection is known to throw a FileNotFoundException exception on getInputStream() if the server returns a response code greater than or equal to 400

Use conn.getErrorStream() to get the input stream when the response status is not 200
Check this:

BufferedInputStream inputStream = null;

int status = conn.getResponseCode();

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

And use it in your reader as:

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

Upvotes: 1

Related Questions