jellyfish
jellyfish

Reputation: 8018

Android: AndroidHttpClient - how to set timeout?

I have followed the instructions of kuester2000's answer, but my timeout settings don't seem to work.

try
{
    int timeout = 3000;
    URL myURL = //some valid URL

    AndroidHttpClient = AndroidHttpClient.newInstance("name");
    HttpGet httpGet = new HttpGet(myURL.toExternalForm());

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
    HttpConnectionParams.setSoTimeout(httpParams, timeout);

    HttpResponse response = httpClient.execute(httpGet);

    //...
}
catch (SocketTimeoutException e)
{
    e.printStackTrace();
}
catch (ConnectTimeoutException e)
{
    e.printStackTrace();
}
catch (IOException e)
{
    e.printStackTrace();
}
//...

However, the timeout value doesn't change anything.

In the answer I linked, it also says:

The connection timeout throws "java.net.SocketTimeoutException: Socket is not connected" and the socket timeout "java.net.SocketTimeoutException: The operation timed out".

But I get neither. Instead I get "org.apache.http.conn.ConnectTimeoutException: Connect to ... timed out"

so can anybody help me? where is the mistake?

Upvotes: 7

Views: 24643

Answers (4)

Learn OpenGL ES
Learn OpenGL ES

Reputation: 4960

After reading around, here's how I did it using the params straight from the default client:

HttpClient client = new DefaultHttpClient();
HttpParams params = client.getParams();
HttpConnectionParams.setConnectionTimeout(params, 3000);
HttpConnectionParams.setSoTimeout(params, 3000);

Original credit goes to http://www.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/

Upvotes: 0

user484261
user484261

Reputation:

The other option to set on the client itself:

AndroidHttpClient client = AndroidHttpClient.newInstance("Client V/1.0");
HttpConnectionParams.setConnectionTimeout(this.client.getParams(), 3000);
HttpConnectionParams.setSoTimeout(this.client.getParams(), 5000);

This should result in those particular params being set...

HTH

Upvotes: 5

jellyfish
jellyfish

Reputation: 8018

I did miss to attach the params to my http request, but the proper way to do this in my example is

httpGet.setParams(httpParams);

before calling httpClient.execute(httpGet).

Just added that line and it worked fine.

Upvotes: 6

theomega
theomega

Reputation: 32051

You do not use the httpParams params, they must be provided to the HTTPClient. So it won't work like this. In the anwer you linked, the order is correct! Try the following order: Create the Params first and supply them to the HTTPClient.

HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);

HttpClient client = new DefaultHttpClient(httpParameters);
HttpGet request = new HttpGet(url);

HttpResponse response = client.execute(request);

Upvotes: 9

Related Questions