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

时间:2017-08-16 04:42:09

标签: android connection-timeout

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

当互联网缓慢应用程序崩溃时。怎么能在asyntask中检查连接超时。

我创建了一个应用程序,有时连接到Web服务以获取数据,我使用异步任务

当用户可以选择是否要重试或取消时,我想在连接超时时建立警告对话框,如果他们选择重试则会尝试重新连接

 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();


    }



   }

5 个答案:

答案 0 :(得分:1)

使用这两个catch块来处理ConnectionTimeOut和socketTimeOut Exceptions

        catch (SocketTimeoutException bug) {
            Toast.makeText(getApplicationContext(), "Socket Timeout", Toast.LENGTH_LONG).show();
        } 
        catch (ConnectTimeoutException bug) {
            Toast.makeText(getApplicationContext(), "Connection Timeout", Toast.LENGTH_LONG).show();
        } 

答案 1 :(得分:1)

对于连接超时,在catch块中添加SocketTimeoutException并使其崩溃,因为没有空检查,您正试图修剪onPostExecute

中的字符串

你应该这样做,并在使用状态之前检查

if(TextUtil.isEmpty(status)) {
   pdlg.dismiss();
   // We are getting empty response
   return;
}
String status1=status.trim();

答案 2 :(得分:1)

您要做的事情是先前在一些很棒的网络库中完成的。所以我建议你使用widley使用过的一个网络库。 截击。

或者,如果您想了解,您只需检查响应状态(或状态代码应为408.我猜连接超时)如果它将返回“连接超时”,那么您可以将您的代码调用到http客户端再次执行你的任务,你也可以添加重试次数尝试2-3次,然后放弃并发送响应onpostexecute方法。

希望这有帮助。

答案 3 :(得分:1)

您可以在代码中捕获连接超时异常,然后根据您的要求设置状态,并在onPostExecute中检查该状态以显示警告对话框

try {
            URL url = new URL("http://....login.php");
            String param = "username=" + uname + "&password=" + pass;
    // Your URL connection code here
catch (ConnectTimeoutException e) {
        Log.e(TAG, "Timeout", e);
        status="timeout"
    } catch (SocketTimeoutException e) {
        Log.e(TAG, " Socket timeout", e);
        status="timeout"
    }
onPostExecute

中的

if (status.equals("timeout")) {
    // Show Alert Dialog.
}

答案 4 :(得分:1)

您可以使用getErrorStream()

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

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

检查this答案了解更多详情..

根据它返回的doc

  

错误流(如果有),如果没有错误,则返回null   连接未连接或   服务器未发送有用数据