Cancel / abort connection from connection pool ThreadSafeClientConnManager
I am using ThreadSafeClientConnManager to manage a pool of client connections because my application has multiple threads connecting to the web server at the same time.
Abstract code example:
HttpClient httpClient;
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(parameters,schReg);
httpclient = new DefaultHttpClient(conMgr, parameters);
Now it can be said that a large file is being loaded in this thread, but then the user of my application switches to another activity / screen. Therefore the file is useless and I would like to terminate this download connection.
In ThreadSafeClientConnManager I found this method:
public ClientConnectionRequest requestConnection (HttpRoute route, Object state)
Returns a new ClientConnectionRequest from which the ManagedClientConnection can be obtained or the request can be aborted .
So far I have used:
HttpGet httpRequest = new HttpGet(URL_TO_FILE);
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
[...]
Now from what I understand I should be using:
httpclient.getConnectionManager().requestConnection(HttpRoute route, Object state);
And this is where I got stuck. I guess for the route I can just use new HttpRoute(new HttpHost("10.0.0.1"))
or whatever my server is, but what to add to Object state
?
And secondly, as soon as I have ClientConnectionManager
, I can call getConnection(long timeout, TimeUnit tunit)
. But then from there, how do I do it, I execute mine HttpGet httpRequest = new HttpGet(URL_TO_FILE);
as before with help HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
?
I went through the documentation and tried several different things, but I was unable to get a working solution. Therefore any suggestions and / or code examples are more than welcome.
source to share
You just need to make a call httpRequest.abort()
and the connection should be closed.
With a large file, you must process the loop data. You can just check the cancellation 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 using pooling or keepalive, the interrupted connection cannot be returned to the pool and must be closed. In older versions there was a bug that the connection is being kept in memory and this clogs the next request. I think this has all been fixed.
source to share