1

I have an Android app that connects in a server searching for updates. If the server takes a long time to respond (+500ms), I have to finish my method and continue with the program.

I already set the readTimeout and connectTimeout to 500 ms, but even then my method are taking about 30 seconds in this line: c.connect();

This is my code:

HttpURLConnection c = (HttpURLConnection) updateUrl.openConnection();
c.setConnectTimeout(500);
c.setReadTimeout(500);
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();  // the program stops here

What I need to do?

jnthnjns
  • 8,962
  • 4
  • 42
  • 65
eliangela
  • 253
  • 2
  • 5
  • 21
  • Check out [this related question and answer](http://stackoverflow.com/a/11583328/1134705) – jnthnjns Aug 17 '12 at 13:56
  • Thaks for the answer, Asok, But I am trying to connect in a local server. The server IP is 192.168.16.150. The URL connect has this value: `http://192.168.16.150/service/android/update/myUpdate.apk`. – eliangela Aug 17 '12 at 14:19
  • 1
    This problem occurs only in some smartphones. I think this occurs only in Android 2.3. In android 2.2 and 4.0 everthing is normal. I'm not using AsyncTask because I need connect for only 500 ms, and I did not think necessary. – eliangela Aug 17 '12 at 14:32
  • Accidentally deleted my comment, sorry, anyway I asked what API level you're on because `HttpURLConnection` "has more bugs" on Eclair (5-7) and Froyo (8) – jnthnjns Aug 17 '12 at 14:34
  • Thanks a lot, Asok!! I solved using org.apache.http.client.HttpClient. – eliangela Aug 17 '12 at 20:25

1 Answers1

1

Thanks a lot, Asok!! I solved using org.apache.http.client.HttpClient:

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

HttpGet httpget = new HttpGet(updateUrl.toURI());
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.setParams(httpParameters);

HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();

//download file.....
eliangela
  • 253
  • 2
  • 5
  • 21
  • +1 Sorry I didn't get back to you sooner. I was going to suggest `HttpClient`. I would suggest doing a API check, if device is pre-8 then use `HttpClient` else `HttpURLConnection`, Google has come out and said that they are going to support `HttpURLConnection` for future versions. – jnthnjns Aug 20 '12 at 13:43
  • 1
    In gingerbread HttpURLConnnection takes double time as set in setConnectTimeout() i.e. if I set time to 30 secs it time out after 1 min, if I set time as 1 min it time outs after 2 minutes. Does any work around exists for that ? – Sachchidanand Oct 10 '12 at 09:12