Search code examples
androidconnectionhttpclient

Android: setting connection time out for HttpPost


Actually this is what i must do to set the Connection Timeout (from this answer by kuester2000):

HttpGet httpPost = new HttpGet("www.xxxx.com/method");
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);
HttpResponse response = httpClient.execute(httpGet);

but in my application i make the httpClient as a Static field in the MainActivities and use it in all the other Activities. Just to have session.

so, should i have this code in all the Activities:

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);

and then

MainActivity.httpClient.setParams(httpParameters);

I just want to know, how i can set the params in the MainActivity and just use the httpClient in all the other Activitites rather than setting the params in every Activity.

Thank You


Solution

  • try this:

    create variables like:

        private static final long CONN_MGR_TIMEOUT = 10000;
        private static final int CONN_TIMEOUT = 50000;
        private static final int SO_TIMEOUT = 50000;
    

    and use this code with httppost:

        ConnManagerParams.setTimeout(params, CONN_MGR_TIMEOUT);
        HttpConnectionParams.setConnectionTimeout(params, CONN_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);