3

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?

5
  • maybe you should not use constants which are defined elsewhere ;) Utils.DEFAULT_CONNECT_TIMEOUT_MILLIS Commented Jul 24, 2017 at 12:32
  • Updated the code, I'm using a 15000 in that constant Commented Jul 24, 2017 at 12:33
  • where do you read/send something? Commented Jul 24, 2017 at 12:34
  • where do you catch java.net.SocketTimeoutException? " If the timeout expires before the connection can be established, a java.net.SocketTimeoutException is raised" Commented Jul 24, 2017 at 12:35
  • @WilliMentzel I only posted the main lines in the code. But they are wrapped in a try-catch and yes a SocketTimeoutException is raised but I need to wait 60 seconds instead of 15 Commented Jul 24, 2017 at 12:39

1 Answer 1

4

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.

Several things can lead to such insane timeouts:

  • DNS server not reachable (UDP port 53), but ICMP is filtered, so the client cannot fail fast
  • local firewall on DNS server dropping packets on closed TCP ports instead of sending RST
  • intermediate firewalls blocking ICMP messages
  • lookups performed over IPv6, but missing IPv6 connectivity
  • AAAA record lookups before A record lookup
  • your DNS server performs full recursion but no caching. Clients should always query a DNS cache, never a recursor only.

Workaround: You may perform the lookup before sending the request, so the result is already pre-cached.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.