问题描述:

I've got a Android app which is written to response to a web query that replies with a JSON response. When the query is correctly formatted, it all works fine. However when the query is wrong, the code crashes and I get the following in the stack trace:

java.io.FileNotFoundException: https://******

I've put ***** in place of the query I placed for privacy here.

If I put the same query in a browser I get the following response:

{"statusCode":401,"error":"Unauthorized","message":"Missing authentication"}

My question is - why is my code throwing an error instead of seeing this as a valid JSON response that I could then parse?

This is my code:

@Override

protected String doInBackground(String... params) {

try {

URL u = new URL(params[0]);

HttpURLConnection conn = (HttpURLConnection) u.openConnection();

conn.setRequestMethod("GET");

conn.connect();

InputStream is = conn.getInputStream();

// Read the stream

byte[] b = new byte[1024];

ByteArrayOutputStream baos = new ByteArrayOutputStream();

while ( is.read(b) != -1) {

baos.write(b);

}

String JSONResp = new String(baos.toByteArray());

return JSONResp;

}

catch(Throwable t) {

t.printStackTrace();

}

return null;

}

网友答案:

you can check the status code of httpurlconnection object using below code:

 if(conn.getResponseCode()==HttpURLConnection.HTTP_ACCEPTED)
            {
                //handle the accepted response
            }
            else
            {
                //handle the failed response
            }
网友答案:

you should use getErrorStream() to read the error stream of your backend call

Returns an input stream from the server in the case of an error such as the requested file has not been found on the remote server. This stream can be used to read the data the server will send back.

InputStream is = null;
if (responseCode == 200) {
  is = urlConnection.getInputStream();
} else {
  is = urlConnection.getErrorStream();
}
网友答案:

Use the following code instead to get the json response form server:

 private InputStream is = null;
   private String jsonString = "";
   private JSONObject jsonObj = null;

    public JSONObject getJSONFromUrl(final String url) { //url is your url

            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();

                is = httpEntity.getContent();

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {

                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                if (sb.length() != 0)
                    jsonString = sb.toString();
            } catch (Exception e) {
                Log.e("_TAG", "Buffer Error: " + e.getMessage());
            }
            try {
                jsonObj = new JSONObject(jsonString);
            } catch (JSONException e) {
                Log.e("_TAG", "Parsing Error: " + e.getMessage());
            }
            return jsonObj;
        }

now get the statusCode from returned jsonObj by above method.

相关阅读:
Top