Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to stop a HttpClient's execution in an AsyncTask?

I have an AsyncTask that handles a rather long download, using HttpClient. I'd like to stop the execution of this request if the user finishes the Activity that starts it. How can I achieve this?

So I started the AsyncTask, HttpClient is in execute(), processing a GET request, is there a way to terminate this?

like image 491
Zsombor Erdődy-Nagy Avatar asked Jun 22 '11 17:06

Zsombor Erdődy-Nagy


1 Answers

  1. Call AsyncTask#cancel to discard pending task
  2. according to HttpClient docs, use HttpUriRequest#abort() to abort http request

1.4. Aborting requests

In some situations HTTP request execution fails to complete within the expected time frame due to high load on the target server or too many concurrent requests issued on the client side. In such cases it may be necessary to terminate the request prematurely and unblock the execution thread blocked in a I/O operation. HTTP requests being executed by HttpClient can be aborted at any stage of execution by invoking HttpUriRequest#abort() method. This method is thread-safe and can be called from any thread. When an HTTP request is aborted its execution thread - even if currently blocked in an I/O operation - is guaranteed to unblock by throwing a InterruptedIOException

like image 179
shaobin0604 Avatar answered Nov 01 '22 02:11

shaobin0604