HttpClient Timeout

July 26, 2013

By default, HttpClient doesn't have a socket timeout. I've encountered a situation where the server didn't respond at all, and the HttpClient just sat there until it was restarted.

Version 3

To add a timeout to Http Client version 3:

HttpClient lClient = new HttpClient();
int lTimeoutMilliseconds = 10 * 1000);
lClient.getParams().setParameter("http.socket.timeout", new Integer(lTimeoutMilliseconds));
lClient.getParams().setParameter("http.connection.timeout", new Integer(lTimeoutMilliseconds));
lClient.getParams().setSoTimeout(lTimeoutMilliseconds);

Version 4

To add a timeout to Http Client version 4:

HttpClient lClient = new HttpClient();
HttpParams lParams = lClient.getParams();
int lTimeoutMilliseconds = 10 * 1000);
HttpConnectionParams.setConnectionTimeout(lParams, lTimeoutMilliseconds);
HttpConnectionParams.setSoTimeout(lParams,  lTimeoutMilliseconds);