Sunday, July 15, 2012

Resolving HTTP Connection Timeout with Android applications

Response time of any application greatly matters especially those dealing with network operations. Sometimes the response from the server is reasonable but at times servers get busy and takes much time in responding. In such situation, we generally set timeout (in the range of 20-30 seconds) for method execution and handle the operation accordingly. This range of timeout is fair for web application but coming to mobile devices the response time has to be much quicker in the range of 3-5 seconds.

We define the connection timeout as follows:

HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 3000);

Here in the above snippet the connection timeout is set to 3000 milliseconds or 3 seconds. But executing the operation, we will notice that the execution does not return after 3 seconds though set rather it waits for a long time. In order to resolve this issue, along with setting the connection timeout, we also need to set the socket timeout as follows:

HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 3000);
HttpConnectionParams.setSoTimeout(params, 3000);

Now executing the operation, we will notice that the execution of code block returns in 3 seconds.

Hope this solves your problem…
Happy programming !!!

No comments: