【问题标题】:AsyncTask connection timeoutAsyncTask 连接超时
【发布时间】:2016-04-30 19:39:33
【问题描述】:

我想设置连接尝试超时,例如 10 秒。但我不太擅长线程或任何网络技术。而且我不知道下一步该怎么做。

这是我的课:

 class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(RecipeActivity.this);
        dialog.setMessage("Loading, please wait");
        dialog.setTitle("Connecting to server");
        dialog.show();
        dialog.setCancelable(false);
    }


    @Override
    protected Boolean doInBackground(String... urls) {
        try {

            HttpGet httpPost = new HttpGet(urls[0]);
            HttpClient httpClient = new DefaultHttpClient();
            HttpResponse response = httpClient.execute(httpPost);


            int status = response.getStatusLine().getStatusCode();

            if (status == 200) {
                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity);

                JSONArray array = new JSONArray(data);

                for (int i = 0; i < array.length(); i++) {
                    JSONObject object = array.getJSONObject(i);

                    Recipe rec = new Recipe();
                    rec.setName(object.getString("name"));
                    rec.setImage(object.getString("image"));
                    rec.setCalories(object.getInt("calories"));
                    rec.setIngredients(object.getString("ingredients"));
                    rec.setInstructions(object.getString("instructions"));
                    rec.setTime(object.getString("time"));
                    rec.setDescription(object.getString("description"));
                    rec.setNumberIngred(object.getString("numberingred"));
                    recipes.add(rec);
                }
                return true;
            }

        } catch (ParseException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    protected void onPostExecute(Boolean result) {
        dialog.cancel();
        adapter.notifyDataSetChanged();
        if (result == false)
            Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();

    }
}

【问题讨论】:

  • 有趣的是,您将 HttpGet 获取对象命名为 httpPost

标签: android multithreading asynchronous


【解决方案1】:

我在 SO 上找到了答案 here

但是,如果您发现 AsyncTasks 很困难,那么您可以通过使用诸如 OkhttpVolley 之类的库来简化它。

【讨论】:

    猜你喜欢
    • 2012-11-14
    • 1970-01-01
    • 2022-01-21
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 2013-09-03
    • 2011-08-05
    相关资源
    最近更新 更多