Florian Peschka Florian Peschka - 1 year ago 191
Java Question

HttpClient stuck without any exception

I'm developing a long-running application that heavily uses the HttpClient from apache.

On my first test run, the application worked perfectly until it just got stuck. It wasn't stopped, it didn't throw any exception, it just sits there doing nothing.

I did a second run just now and stopped the time and it stopped after approx. 24 hours of contant running. Additionally I noticed that the internet connection of my laptop on which I had it running was terminated at the exact moment the application got stuck. I had to reboot my WLAN adapter in order to the the net running again.

The application though, didn't return to working after the connection was up again. And now, it's stuck again.

Is there any timeout controller I'm not aware of in the HttpClient? Why doesn't my application throw an exception when the connection is down?

The part that uses the client looks as follows;

public HttpUtil(ConfigUtil config) {
this.config = config;

client = new DefaultHttpClient();
client.getParams().setParameter(HttpProtocolParams.USER_AGENT, this.config.getProperty("httputil.userAgent"));

public String getContentAsString(String url) throws ParseException, ClientProtocolException, IOException {
return EntityUtils.toString(
new HttpGet(url)).getEntity());

The application repeatedly calls
on the URLs it needs.

Answer Source

This code is now deprecated (get HttpParams, etc). A better way is:

RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();

HttpGet httpGet = new HttpGet(url);    
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setSocketTimeout(5000).setConnectTimeout(5000).setConnectionRequestTimeout(5000).build();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download