Proper timeout handling with Apache HttpClient
August 24th, 2009 by Brian | 5 Comments | Filed in workI’ve seen some really bad things happen when developers don’t code in proper timeout handling. Occasionally I’ve been asked what the best way to handle timeouts is – so I thought I’d share my take on it:
HttpConnectionManagerParams params = connectionManager.getParams();
params.setConnectionTimeout(connectiontimeout); //set connection timeout (how long it takes to connect to remote host)
params.setSoTimeout(sotimeout); //set socket timeout (how long it takes to retrieve data from remote host)
HttpMethodBase baseMethod = null;
try {
HttpClient httpClient = new HttpClient(connectionManager);
httpClient.getParams().setParameter("http.connection-manager.timeout", poolTimeout); //set timeout on how long we’ll wait for a connection from the pool
baseMethod = new GetMethod(…);
int statusCode = httpClient.executeMethod(…);
…
}
catch (ConnectTimeoutException cte ){
//Took too long to connect to remote host
}
catch (SocketTimeoutException ste){
//Remote host didn’t respond in time
}
catch (Exception se){
//Some other error occurred
}
finally {
if (baseMethod != null)
baseMethod.releaseConnection();
}
Tags: apache, httpclient, java, timeouts

