Why timeout value is not respected by android HttpURLConnection?

后端 未结 2 452
忘掉有多难
忘掉有多难 2020-12-31 05:52

I have the following code block:

try {
    URL url = new URL(\"http://site-to-test.com/nonexistingpage.html\");

    HttpURLConnection urlc = (HttpURLConnect         


        
2条回答
  •  误落风尘
    2020-12-31 06:34

    After deep investigations and alot of trails, I found that the best way to implement a timer for AsyncTask (or Service, the object you used to perform background work) away from the HTTP connection class, as sometimes when you disconnect the HTTP connection, this doesn't interrupt the web call, I implemented this class to be used when you need timeout check for your HTTP connection

    public abstract class AsyncTaskWithTimer extends
        AsyncTask {
    
        private static final int HTTP_REQUEST_TIMEOUT = 30000;
    
        @Override
        protected Result doInBackground(Params... params) {
            createTimeoutListener();
            return doInBackgroundImpl(params);
        }
    
        private void createTimeoutListener() {
            Thread timeout = new Thread() {
                public void run() {
                    Looper.prepare();
    
                    final Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
    
                            if (AsyncTaskWithTimer.this != null
                                    && AsyncTaskWithTimer.this.getStatus() != Status.FINISHED)
                                AsyncTaskWithTimer.this.cancel(true);
                            handler.removeCallbacks(this);
                            Looper.myLooper().quit();
                        }
                    }, HTTP_REQUEST_TIMEOUT);
    
                    Looper.loop();
                }
            };
            timeout.start();
        }
    
        abstract protected Result doInBackgroundImpl(Params... params);
    }
    

    A Sample for this

    public class AsyncTaskWithTimerSample extends AsyncTaskWithTimer {
    
        @Override
        protected void onCancelled(Void void) {
            Log.d(TAG, "Async Task onCancelled With Result");
            super.onCancelled(result);
        }
    
        @Override
        protected void onCancelled() {
            Log.d(TAG, "Async Task onCancelled");
            super.onCancelled();
        }
    
        @Override
        protected Void doInBackgroundImpl(Void... params) {
            // Do background work
            return null;
        };
     }
    

提交回复
热议问题