Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancelling Http connection in android

I am using org.apache.http and I've this code:

DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);

HttpResponse resp = client.execute(get);
HttpEntity entity = resp.getEntity();

InputStream input = entity.getContent();

...
//Read the bytes from input stream

This is the code I am using to download files over Http, I want to cancel the connection(may be user chooses to) What is the graceful way to close the connection. I found 2 ways, Both cancels the download.

  1. Closing inputsteram, input.close(); which causes IOException.
  2. Aborting HttpGet object, get.abort() causes SocketException.

I have try catch, so no erros, but without throwing exception, is there a way to cancel or abort the connection?

What is the right way to go about it ?

like image 756
sat Avatar asked Sep 03 '11 07:09

sat


People also ask

How do I terminate HTTP request?

You can abort the current HTTP request using the abort() method, i.e., after invoking this method, on a particular request, execution of it will be aborted. If this method is invoked after one execution, responses of that execution will not be affected and the subsequent executions will be aborted.

How to cancel Async task Android?

A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns.


1 Answers

The proper way doing this is sending FIN value to the server side.

How ever in android you do not have the option to be involved in this level, so you can implement by your self using C, or use one of the methods you mention in your question.

like image 151
Ilya Gazman Avatar answered Sep 20 '22 15:09

Ilya Gazman