如何检查url是否存在以获取json数据

时间:2016-07-15 18:35:14

标签: android json

我正在获取不同book_name&的json数据。它工作正常。但如果书不存在我的应用程序崩溃。我知道JsonObject获取空数据,但我希望它做一些事情,而不是在找不到书时崩溃。我的代码是:    `

   public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

    final String TAG = "AsyncTaskParseJson.java";

    // set your json string url here
   Intent po=getIntent();
    String bok=po.getStringExtra("bookname");
    String newName = bok.replaceAll("\\s", "%20");
    String yourJsonStringUrl = "http://www.bsservicess.com/photoUpload/star_avg.php?bookName="+newName;

    // contacts JSONArray
    JSONArray dataJsonArr = null;
    @Override
    protected void onPreExecute() {}


    protected String doInBackground(String... arg0) {
        if(exists(yourJsonStringUrl)) {
        try {
            JSONParser jParser = new JSONParser();

            // get json string from url

            JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);



                // get the array of users
                dataJsonArr = json.getJSONArray("result");
                JSONObject c = dataJsonArr.getJSONObject(0);
                //    na=c.getString("avg");

                ratenumS = c.getString("avg");
                numberS = c.getString("num");
                starts = Float.parseFloat(c.getString("avg"));


        } catch (JSONException e) {
            e.printStackTrace();
        }
        }else{
            starts=0;
            numberS="0";
        }

        return null;
    }

    @Override
    protected void onPostExecute(String strFromDoInBg) {
        super.onPostExecute(strFromDoInBg);
        ratenum.setText(ratenumS);
        number.setText("("+numberS+")");
        netRate.setRating(starts);
     //   Toast.makeText(mybookview.this, Float.toString(starts),Toast.LENGTH_SHORT).show();
    }

Plz帮助我。       `

       public JSONObject getJSONFromUrl(String url) {

    // make HTTP request
    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 = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();

    } catch (Exception e) {
        Log.e(TAG, "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e(TAG, "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;
}

}`

2 个答案:

答案 0 :(得分:1)

// get json string from url

JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
if(json == null){
    //url parsing didn't work
    return;
}

答案 1 :(得分:0)

您需要处理异常,在应用崩溃的地方添加try catch。