Why is URLConnection timeout after 6 minutes instead of 5 seconds?

I am copying this method verbatim from my application, which is not yet complete, but it is trying to provide me with a trace of the timeout stack if everything goes not so smoothly:

protected boolean isHttpAlive() { boolean isHttpOk = false; HttpURLConnection httpConnection = null; try { URL gurl = new URL("http://www.amazon.com/"); URLConnection connection = gurl.openConnection(); connection.setConnectTimeout(5 * 1000); // 5 seconds! httpConnection = (HttpURLConnection) connection; int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) isHttpOk = true; } catch (Exception e) { e.printStackTrace(); } finally { if (httpConnection != null) httpConnection.disconnect(); } return isHttpOk; } 

Now on one of my test devices (Droid), when there is a problem, I get an exception , but only after 6 minutes and 36 seconds , and not 5 seconds, as I installed in the above code.

A timeout exception has been getResponseCode() for getResponseCode() .

Why?

What am I missing?

+7
source share
2 answers

My best guess is that the URL you are connecting to, Amazon in this case has multiple IPs.

According to the warning in the documentation :

if the host name is resolved for several IP addresses, this client will try each one in RFC 3484 order. If the connection to each of these addresses fails, several timeouts will elapse before the connection attempt raises an exception. Host names that support both IPv6 and IPv4 always have at least 2 IP addresses.


Edit:
I am still learning this because I want to convert my applications from HTTPClient to URLConnection . I am not satisfied, in your case, with a 6 minute timeout.

I also stumbled upon this blog . He also suggests adding connection.setReadTimeout(READ_TIMEOUT_MILLISECONDS); I don’t know if this will help your cause.

+5
source

this king of code is not very useful for checking the connection. The reasons for a poor connection are numerous (each level of the ip stack may have a problem). For example: you can have a connection and receive one byte per second, without a timeout, but not very fun for the user ... and if you use "www.amazon.com" as a test, they can joke you (i " I did it myself, D)

-one
source

All Articles