I'm using ThreadSafeClientConnManager to manage a pool of client connections, because my application has several threads, which are simultaneously connecting to a webserver.
Abstract sample code:
HttpClient httpClient;
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(parameters,schReg);
httpclient = new DefaultHttpClient(conMgr, parameters);
Now lets say on of this threads is downloading a large file, but then the user of my application is switching to another activity/screen. Therefor the file is needless and I'd like to abort this download connection.
In ThreadSafeClientConnManager I found this method:
public ClientConnectionRequest requestConnection (HttpRoute route, Object state)
Returns a new ClientConnectionRequest, from which a ManagedClientConnection can be obtained or the request can be aborted.
So far I've been using:
HttpGet httpRequest = new HttpGet(URL_TO_FILE);
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
[...]
Now from what I understand, I've to use:
httpclient.getConnectionManager().requestConnection(HttpRoute route, Object state);
And that's the point where I'm stuck. I assume that for the route I can just use new HttpRoute(new HttpHost("10.0.0.1"))
or whatever my server is, but what to put in for Object state
?
And second, as soon as I've the ClientConnectionManager
I can call getConnection(long timeout, TimeUnit tunit)
. But then from there, how I do I execute my HttpGet httpRequest = new HttpGet(URL_TO_FILE);
as I did before with HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
?
I've been gone through the documentation and tried out quite a few different things, but I wasn't able to obtain a working solution. Therefor any suggestions and/or code examples are more than welcome.
You just need to call httpRequest.abort()
and the connection should be closed.
With a large file, you must have a loop process the data. You can just check the cancel status and abort from there,
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
while (instream.read(buf) >= 0) {
if (cancelled)
httpRequest.abort();
// Process the file
}
}
When pooling or keepalive is used, the aborted connection can't be returned to the pool and it must be closed. There was a bug in older versions that the connection is kept alive and it messes up next request. I think this is all fixed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With