HttpURLConnection setConnectTimeout() has no effect

前端 未结 8 1478
刺人心
刺人心 2020-12-04 21:40

I\'m connecting to a simple RSS feed using HTTPUrlConnection. It works perfectly. I\'d like to add a timeout to the connection since I don\'t want my app hanging in the even

8条回答
  •  有刺的猬
    2020-12-04 22:30

    It's caused by:
    1. You are connected to wifi but you dont have internet connection.
    2. You are connected to GSM data but your transfer is very poor.

    In both cases you get a host exception after about 20seconds. In my opinion the best way to get correct is:

    public boolean isOnline() {
            final int TIMEOUT_MILLS = 3000;
            final boolean[] online = {false};
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isConnected()) {
                final long time = System.currentTimeMillis();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            URL url = new URL("http://www.google.com");
                            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                            urlc.setConnectTimeout(TIMEOUT_MILLS);
                            urlc.setReadTimeout(TIMEOUT_MILLS);
                            urlc.connect();
                            if (urlc.getResponseCode() == 200) {
                                online[0] = true;
                            }
                        } catch (IOException e) {
                            loger.add(Loger.ERROR, e.toString());
                        }
                    }
                }).start();
    
                while (((System.currentTimeMillis() - time) <= TIMEOUT_MILLS)) {
                    if ((System.currentTimeMillis() - time) >= TIMEOUT_MILLS) {
                        return online[0];
                    }
                }
            }
            return online[0];
        }
    

    remember - use it in asynctask or service.

    Its simple solution, you are starting new Thread with HttpUrlConnection (remember use start() not run()). Than in while loop you are waiting 3 sec for result. If nothing happend return false. This way let you avoid waiting for host exception and avoid problem with not working setConnectTimeout() when you dont have internet connection.

提交回复
热议问题