HttpURLConnection setConnectTimeout() has no effect

前端 未结 8 1525
刺人心
刺人心 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:22

    I had a similar problem - because the HttpUrlConnection won't time out mid-download. For example, if you turn off wifi when download is going, mine continued to say it is downloading, stuck at the same percentage.

    I found a solution, using a TimerTask, connected to a AsyncTask named DownloaderTask. Try:

    class Timeout extends TimerTask {
        private DownloaderTask _task;
    
        public Timeout(DownloaderTask task) {
            _task = task;
        }
    
        @Override
        public void run() {
            Log.w(TAG,"Timed out while downloading.");
            _task.cancel(false);
        }
    };
    

    Then in the actual download loop set a timer for timeout-error:

                        _outFile.createNewFile();
                        FileOutputStream file = new FileOutputStream(_outFile);
                        out = new BufferedOutputStream(file);
                        byte[] data = new byte[1024];
                        int count;
                        _timer = new Timer();
                        // Read in chunks, much more efficient than byte by byte, lower cpu usage.
                        while((count = in.read(data, 0, 1024)) != -1 && !isCancelled()) { 
                            out.write(data,0,count);
                            downloaded+=count;
                            publishProgress((int) ((downloaded/ (float)contentLength)*100));
                            _timer.cancel();
                            _timer = new Timer();
                            _timer.schedule(new Timeout(this), 1000*20);
                        }
                        _timer.cancel();
                        out.flush();
    

    If it times out, and won't download even 1K in 20 seconds, it cancels instead of appearing to be forever downloading.

提交回复
热议问题