自从JDK1.5以后java.net.URLConnection加入了setConnectTimeout(int timeout),但是也有办法在JDK1.5以前获得这个功能。
Adding Socket Timeout to java.net.URLConnection
HTTPClient Version 0.3-3
The Jakarta Commons HttpClient
另外,可以通过以下两个语句来设置相应的超时:
System.setProperty("sun.net.client.defaultConnectTimeout", 连接超时毫秒数);
System.setProperty("sun.net.client.defaultReadTimeout", 读数据超时毫秒数);
参见:http://java.sun.com/j2se/1.4.2/docs/guide/net/properties.html
google:set Timeout on URLConnection
Well performing NIO code is a Good Thing. But getting details of how to do it right is difficult. The examples supplied with the JDK are complete noddy. There's a link on Sun's site to an example but that has a race condition. O'Reilly's NIO book cops out on how to use Selector properly. The thing that could make that book useful.