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

前端 未结 5 1197
面向向阳花
面向向阳花 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 03:12

    Since Java 1.5, it is possible to set the read timeout in milliseconds on the underlying socket via the 'setReadTimeout(int timeout)' method on the URLConnection class.

    Note that there is also the 'setConnectTimeout(int timeout)' which will do the same thing for the initial connection to the remote server, so it is important to set that as well.

提交回复
热议问题