I'm trying to properly configure the timeouts for my connections using HttpURLConnection.
My problem is that after the getResponseCode() call It always timeouts after 60 seconds instead of the value I set. My code:
URL url = new URL(uri.toString());
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setConnectTimeout(15000);
connection.setReadTimeout(15000);
int responseCode = connection.getResponseCode();
What do I am missing?
I also encountered the same kind of problem a few days back, So did some research.
My problem is that after the getResponseCode() call It always timeouts after 60 seconds instead of the value I set.
this is because InetAddress.getByName(String) does a DNS lookup. That lookup is not part of the connection timeout.
The JDK doesn't let you specify a timeout here. It simply uses the timeouts of the underlying name resolution mechanism.
Anyway, I suspect the effect is not limited to Java. You should be able to observe the same timeouts using nslookup or the host command from a terminal. In a "normal" environment DNS lookup timeouts should be of the order of 1-3 seconds, but not 20 seconds. So I strongly suspect your network setup is broken.
Workaround: You may perform the lookup before sending the request, so the result is already pre-cached.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With