Why timeout value is not respected by android HttpURLConnection?

主宰稳场 提交于 2019-11-30 08:42:29

It appears that Java URLConnection provides no fail-safe timeout on reads

The solution is, as the article explains, to use a separate Thread for timing, and disconnect the HttpURLConnection manually once the timer thread is done.

Ayman Mahgoub

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<Params, Progress, Result> extends
    AsyncTask<Params, Progress, Result> {

    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<Void, Void, Void> {

    @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;
    };
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!