I'm writing an application that connects to a webservice and I don't want it to wait too long if it can't get a connection. I therefore set the connectionTimeout of the httpparams. But it doesn't seem to have any effect whatsoever.
To test I turn of my WLAN temporarily. The application tries to connect for quite some time (way more than the 3 seconds I want) and then throws an UnknownHostException.
Here is my code:
try{
HttpClient httpclient = new DefaultHttpClient();
HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 3000);
HttpConnectionParams.setSoTimeout(params, 3000);
httppost = new HttpPost(URL);
StringEntity se = new StringEntity(envelope,HTTP.UTF_8);
httppost.setEntity(se);
//Code stops here until UnknownHostException is thrown.
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient.execute(httppost);
HttpEntity entity = httpResponse.getEntity();
return entity;
}catch (Exception e){
e.printStackTrace();
}
Anyone have any ideas what I missed?
With the marked solution I am still getting a UnknownHostException after 30+ seconds. In this case the device is connected to a wifi router but there is no internet access.
The approach taken was to kick off an AsyncTask that will just attempt to resolve the hostname. The blocking call checks every 250 ms to see if it succeeded, and after 4 seconds it will cancel the task and return.
This is what I did to solve it:
Then, any time I want to do a web call, this is called at the beginning of the function:
This method works for me :
See: https://stackoverflow.com/a/20031077/2609238
The problem might be in the Apache HTTP Client. See HTTPCLIENT-1098. Fixed in 4.1.2.
The timeout exception tries to reverse DNS the IP, for logging purposes. This takes an additional time until the exception is actually fired.
Try to do it this way:
You then can catch a possible
ConnectTimeoutException
.