How to set HttpResponse timeout for Android in Java How to set HttpResponse timeout for Android in Java android android

How to set HttpResponse timeout for Android in Java


In my example, two timeouts are set. The connection timeout throws java.net.SocketTimeoutException: Socket is not connected and the socket timeout java.net.SocketTimeoutException: The operation timed out.

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);HttpResponse response = httpClient.execute(httpGet);

If you want to set the Parameters of any existing HTTPClient (e.g. DefaultHttpClient or AndroidHttpClient) you can use the function setParams().

httpClient.setParams(httpParameters);


To set settings on the client:

AndroidHttpClient client = AndroidHttpClient.newInstance("Awesome User Agent V/1.0");HttpConnectionParams.setConnectionTimeout(client.getParams(), 3000);HttpConnectionParams.setSoTimeout(client.getParams(), 5000);

I've used this successfully on JellyBean, but should also work for older platforms ....

HTH


If your are using Jakarta's http client library then you can do something like:

        HttpClient client = new HttpClient();        client.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, new Long(5000));        client.getParams().setParameter(HttpClientParams.SO_TIMEOUT, new Integer(5000));        GetMethod method = new GetMethod("http://www.yoururl.com");        method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(5000));        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,        int statuscode = client.executeMethod(method);