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,267
  • 4
  • 22
  • 41

1 Answers1

33

Use the HttpConnectionParams of your DefaultHttpClient::

final HttpParams httpParameters = yourHttpClient.getParams();

HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeOutSec * 1000);
HttpConnectionParams.setSoTimeout        (httpParameters, socketTimeoutSec * 1000);
Shlublu
  • 10,917
  • 4
  • 51
  • 70
  • 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