turbomanage / basic-http-client

Automatically exported from code.google.com/p/basic-http-client
73 stars 25 forks source link

Enhancement: allow requests to be aborted by calling somHttpResponse.abort() #14

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1. AndroidHttpClient httpClient = new AndroidHttpClient("www.example.com");
2. HttpResponse response = httpClient.get( "/", null );

What is the expected output? What do you see instead?
3. I expect to be able to abort the connection using, for example, 
response.abort(), at which point any code blocked at "HttpResponse response = 
httpClient.get( "/", null )" should return immediately (perhaps returning null 
or throwing an exception).

Additional information.
This is especially needed on mobile devices such as Android where a user may 
suddenly realise that she is using expensive mobile data and wishes to drop a 
network request immediately.

Original issue reported on code.google.com by gallalSF@gmail.com on 26 Feb 2013 at 2:21

GoogleCodeExporter commented 9 years ago
This is a potentially far-reaching request. I can give you a few pointers and I 
think you could take a stab at this yourself and post back how it works out. In 
order to cancel a request in progress, you would need to subclass 
BasicRequestHandler (let's call it CancelableRequestHandler) and add a cancel() 
method that sets a boolean field cancelled. Then override readStream() and 
inside the while statement, add an if statement to check the cancelled field 
and throw an IOException if it's true. The exception will get caught upstream, 
properly closing the InputStream and HttpUrlConnection.

Invoke the cancel() method like this:
CancelableRequestHandler reqHandler = new CancelableReqestHandler() {
// implement onSuccess, onError
});
AndroidHttpClient client = new AndroidHttpClient(baseUrl, requestHandler);
...
requestHandler.cancel();

Alternatively, it's possible that in CancelableRequestHandler, you could 
delegate readStream() to a CancelableStreamReader. Then CRH.cancel() would 
invoke CSR.cancel(), which would attempt to close the InputStream. I'm honestly 
not sure what happens, though, if you try to close an input stream that's being 
read in another thread, as it would be here because the read happens in an 
AsyncTask.

A more robust implementation would involve using a Handler() to pass a message 
to the DoHttpRequestTask in progress, or perhaps expose the task itself, but in 
either case the cancellation still has to get propagated down to a 
RequestHandler as I've outlined above.

Original comment by turboman...@gmail.com on 26 Feb 2013 at 7:34

GoogleCodeExporter commented 9 years ago

Original comment by turboman...@gmail.com on 25 Mar 2013 at 8:04