How can I set a timeout against a BufferedReader based upon a URLConnection in Java?

前端 未结 5 1207
面向向阳花
面向向阳花 2020-12-19 02:25

I want to read the contents of a URL but don\'t want to \"hang\" if the URL is unresponsive. I\'ve created a BufferedReader using the URL...



        
5条回答
  •  清歌不尽
    2020-12-19 02:57

    I have been working on this issue in a JVM 1.4 environment just recently. The stock answer is to use the system properties sun.net.client.defaultReadTimeout (read timeout) and/or sun.net.client.defaultConnectTimeout. These are documented at Networking Properties and can be set via the -D argument on the Java command line or via a System.setProperty method call.

    Supposedly these are cached by the implementation so you can't change them from one thing to another so one they are used once, the values are retained.

    Also they don't really work for SSL connections ala HttpsURLConnection. There are other ways to deal with that using a custom SSLSocketFactory.

    Again, all this applies to JVM 1.4.x. At 1.5 and above you have more methods available to you in the API (as noted by the other responders above).

提交回复
热议问题