I'm a little confused on how the timeouts in DefaultHttpClient work.
I'm using this code:
private DefaultHttpClient createHttpClient() {
HttpParams my_httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(my_httpParams, 3000);
HttpConnectionParams.setSoTimeout(my_httpParams, 15000);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
ThreadSafeClientConnManager multiThreadedConnectionManager = new ThreadSafeClientConnManager(my_httpParams, registry);
DefaultHttpClient httpclient = new DefaultHttpClient(multiThreadedConnectionManager, my_httpParams);
return httpclient;
}
.
String url = "http://www.example.com";
DefaultHttpClient httpclient = createHttpClient();
HttpGet httpget = new HttpGet(url);
try {
HttpResponse response = httpclient.execute(httpget);
StatusLine statusLine = response.getStatusLine();
mStatusCode = statusLine.getStatusCode();
if (mStatusCode == 200){
content = EntityUtils.toString(response.getEntity());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e){
e.printStackTrace();
}
When 15 seconds have passed and not all data has been received, an exception will be thrown, right? But on which method? I thought it to be the .execute(httpget)
method but that one only tells me it throws ClientProtocolException
and IOException
. Could anyone help me clearifying this?
It does throw an exception on
execute()
. The parent ofSocketTimeoutException
is anIOException
. A catch block handlingIOException
will be able to catch both.Try executing this code.
It results in this exception.
You can always choose to selectively process the exception by catching it and handling
IOException
later.If you look at the Apache docs at http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e249, it notes that connection timeout exceptions are IOException subclasses.
To be more specific, I believe they'll either ConnectTimeoutExceptions if the connection can't be set up within your configured connection timeout, or SocketTimeoutExceptions, if it's set up but no data is received for your configured SO timeout.