android - 如何处理异步任务中的连接超时

标签 android connection-timeout

我有一个问题还没有解决,我需要帮助。

当互联网速度慢时应用程序崩溃。如何在 asyntask 中检查连接超时。

我制作了一个有时会连接到网络服务以获取数据的应用程序,我使用异步任务来完成此操作

当用户可以选择是要重试还是取消时,我想在连接超时时发出警告对话框,如果他们选择重试,它将尝试再次连接

 public class login extends AsyncTask<Void,Void,Void> {

    InputStream ins;
    String status, result, s = null, data = "",js;
    int ss;
    int responseCode;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pdlg.setTitle("Checking");
        pdlg.setMessage("Please wait");
        pdlg.setCancelable(false);
        pdlg.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        StringBuilder sb = new StringBuilder();
        ArrayList al;
        try {
            URL url = new URL("http://....login.php");
            String param = "username=" + uname + "&password=" + pass;
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(15000);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            OutputStream os = connection.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            bw.write(param);
            bw.flush();
            bw.close();

            responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line = "";
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
            }
            data = sb.toString();
            JSONObject json = new JSONObject(data);

            status=json.getString("Status");//{"Login Status":"Success","Receipt Details":"No data available"}

           // js=json.getString("Login");//{"Login":"Failed"}



        } catch (MalformedURLException e) {
            Log.i("MalformedURLException", e.getMessage());
        } catch (IOException e) {
            Log.i("IOException", e.getMessage());
        } catch (JSONException e) {
            Log.i("JSONException", e.getMessage());
        }

        return null;
    }

    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        String status1=status.trim();


      if (status1.equals("Success")) {
    Toast.makeText(getApplicationContext(), "Login Succes  !!", Toast.LENGTH_SHORT).show();

          Intent i = new Intent(Login.this, Home.class);
          startActivity(i);
            finish();
          SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
          SharedPreferences.Editor editor = sharedPreferences.edit();
          editor.putBoolean("first_time", false);
          editor.putString("userrname", uname);
          editor.putString("password",pass);
          editor.apply();
          Toast.makeText(getApplicationContext(),"welcome : "+uname,Toast.LENGTH_LONG).show();

      }

else {
    Toast t=Toast.makeText(Login.this, "Username or Password is Incorrect", Toast.LENGTH_LONG);
          t.setGravity(Gravity.BOTTOM,0,0);
                        t.show();
}

        pdlg.dismiss();


    }



   }

最佳答案

你可以使用 getErrorStream() ,

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream inp;

// if some error in connection 
 inp = connection.getErrorStream();

检查 this回答更多细节..

根据doc它返回

an error stream if any, null if there have been no errors, the connection is not connected or the server sent no useful data

.

关于android - 如何处理异步任务中的连接超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45705237/

相关文章:

Android Recycler Adapter 位置无法正常工作 : onClick handling doesn't work properly

java - 请求路由到主机 android

android - Sherlock Activity 中的两行 ListView

java - 创建一个未索引的文件夹导致 IOException

android - 应用程序启动前未收到 INSTALL_REFERRER

c# - 超时过期异常;找不到哪个连接保持打开状态或者是否有其他问题

parse-platform - 为 Parse 查询设置连接超时

linux - 如何查看sshfs挂载目录是否断开?

android - HttpConnectionParams.setConnectionTimeout混淆

android - 我应该在异步任务的背景中使用 android-async-http 客户端吗?