0

Ive got

 HttpURLConnection urlConnection = null;
        String result = "";
        try {

            String host = "http://www.example.com/json.json";

            URL url = new URL(host);
            urlConnection = (HttpURLConnection) url.openConnection();

            int code = urlConnection.getResponseCode();

            if(code==200){
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                if (in != null) {
                    JSONParser jsonParser = new JSONParser();
                    JSONObject jsonObject = (JSONObject)jsonParser.parse(new InputStreamReader(in, "UTF-8"));
                    result=(String) jsonObject.get("name");
                    System.out.print(jsonObject);
                }
                in.close();
            } else { result="9";}

            return result;
        } catch (MalformedURLException e) {
            result="9";
        } catch (IOException e) {
            result="9";
        }
        catch (ParseException e) {
            e.printStackTrace();
            result="9";
        }

        finally {
            urlConnection.disconnect();
        }
        return result;

When i input valid json data, all is OK, but if i got non json data, i got aplication crash with :

Caused by: java.lang.ClassCastException: java.lang.Long cannot be cast to org.json.simple.JSONObject

I think that

 catch (ParseException e) {
                e.printStackTrace();
                result="9";
            }

should handle this, but no.

So what i must do to avoid situation that aplication will crash when i do not get valid json?

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Sirwiz
  • 15
  • 5

3 Answers3

0

The thrown exception is a ClassCastException. Maybe you can catch that exception also by adding another catch?

catch (ClassCastException e) {
    e.printStackTrace();
    result="9";
}
jljvdm
  • 66
  • 7
0

Try this to make a http request

class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            URL myUrl = null;
            HttpURLConnection conn = null;
            String response = "";
            //String data = params[0];

            try {
                myUrl = new URL("http://www.example.com/json.json");
                conn = (HttpURLConnection) myUrl.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);

                //one long string, first encode is the key to get the  data on your web
                //page, second encode is the value, keep concatenating key and value.
                //theres another ways which easier then this long string in case you are
                //posting a lot of info, look it up.
                String postData = URLEncoder.encode("key", "UTF-8") + "=" +
                        URLEncoder.encode("value", "UTF-8");
                OutputStream os = conn.getOutputStream();

                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                bufferedWriter.write(postData);
                bufferedWriter.flush();
                bufferedWriter.close();

                InputStream inputStream = conn.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    response += line;
                }
                bufferedReader.close();
                inputStream.close();
                conn.disconnect();
                os.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return response;
        }

        @Override
        protected void onPostExecute(String s) {
            try {
                JSONObject jsonObject = new JSONObject(s);
            } catch (JSONException e) {
                //s may not be json
            }
        }
    }
devgun
  • 1,003
  • 13
  • 33
0

Before getting String from Json Object, check whether the Json object is not null and has that string. and then try to get it.

if (jsonObject!=null && jsonObject.has("name"))
 {
     result = jsonObject.get("name");
     System.out.print(result);
  }
Kapil Parmar
  • 881
  • 8
  • 19