11

I have created an Android application where I connect to a remote server php file to retrieve some information. Below is the code for that.

Here I want to add timeout with the connection such as the connection will timeout in 5 seconds.

Any idea how to do this.

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name","test"));

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mysite.com/test.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost); 

Regards,

Shankar

Bhabani Shankar
  • 1,247
  • 4
  • 22
  • 40

2 Answers2

33

Use the HttpConnectionParams of your DefaultHttpClient::

final HttpParams httpParameters = yourHttpClient.getParams();

HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeOutSec * 1000);
HttpConnectionParams.setSoTimeout        (httpParameters, socketTimeoutSec * 1000);
Shlublu
  • 10,693
  • 4
  • 51
  • 69
  • 2
    the time out is all well and good, but how to we catch the time out (the code as it is right now just fails silently when there is a timeout) – J.R. Feb 11 '13 at 16:03
  • When it fails, this code throws an exception that you can catch and handle. – Shlublu Jun 07 '13 at 08:11
  • 1
    By "this" code, I meant the OP's code. Nowadays, according to Android's official blog, it is better to use HttpUrlConnection rather than DefaultHttpClient anyway. – Shlublu Jun 14 '14 at 21:24
3
final HttpParams httpParameters = yourHttpClient.getParams();

HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeOutSec * 1000);
HttpConnectionParams.setSoTimeout        (httpParameters, socketTimeoutSec * 1000);

If that does not work (as in my case). try this which works for me (link)

HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();

// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used. 
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

// Set the default socket timeout (SO_TIMEOUT) 
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
Community
  • 1
  • 1
Phuong
  • 1,281
  • 1
  • 10
  • 6
  • Please be advised that by passing in BasicHttpParams to DefaultHttpClient results in the default HTTP connection params being lost. This means that unless specifically added back in, the User-Agent will not be in the HTTP headers. – Jade Aug 17 '13 at 19:36
  • Good, but HttpConnectionParams is deprecated starting from Apache HttpCore 4.3 – kinORnirvana Jun 10 '16 at 09:40