2

Here is my code :

URL u = new URL("http://www.google.com");
        URLConnection conn = u.openConnection();
        conn.setConnectTimeout(3000);
        conn.connect();

My network connection is sometimes unstable(I've connected to the wireless router but actually my router doesn't have Internet access). When that happens, this code will block for a lone time and finally throws UnknownHostException. Why setConnectTimeout(3000) doesn't work in this case? How to fix this? Thanks!

------------update---------------

My guess is that conn.connect() will query DNS first but there's no time limit for this operation. I've tried Socket class and problem remains. setTimeout() seems do not work for DNS query.

Neo
  • 2,196
  • 5
  • 32
  • 58
  • @fge `u.openConnection()` does not establish the connection to server until `conn.connect()` is called – Neo Jan 28 '15 at 09:13
  • This answer might work, but I haven't tested it. Seems to suggest you can set the DNS timeout on a per-domain basis: http://stackoverflow.com/questions/21084830/how-to-set-the-timeout-for-socket-when-looking-for-host/21085015#21085015 – Mike Tunnicliffe Jan 28 '15 at 09:25

2 Answers2

1

I found a post that can work around it. Use another thread to query DNS to simulate timeout: http://thushw.blogspot.sg/2009/11/resolving-domain-names-quickly-with.html

Neo
  • 2,196
  • 5
  • 32
  • 58
0

Some non-standard implmentation of this method may ignore the specified timeout. See this setConnectTimeout

yanyu
  • 219
  • 2
  • 11
  • 1
    I've noted that. But I'm using Oracle's HotSpot JVM, it doesn't seem like a non-standard implementation. – Neo Jan 28 '15 at 09:30
  • can you try set ConnectTimeout by 1, it throws SocketTimeoutException sometimes and UnknownHostException others. It means ConnectTimeout works. – yanyu Jan 28 '15 at 09:40