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

前端 未结 5 1211
面向向阳花
面向向阳花 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:49

    If you have java 1.4:

    I assume the connection timeout (URLConnection.setConnectTimeout(int timeout) ) is of no use because you are doing some kind of streaming.

    ---Do not kill the thread--- It may cause unknown problems, open descriptors, etc.

    Spawn a java.util.TimerTask where you will check if you have finished the process, otherwise, close the BufferedReader and the OutputStream of the URLConnection

    Insert a boolean flag isFinished and set it to true at the end of your loop and to false before the loop

    TimerTask ft = new TimerTask(){
       public void run(){
         if (!isFinished){
           urlConn.getInputStream().close();
          urlConn.getOutputStream().close();
         }
       }
    };
    
    (new Timer()).schedule(ft, timeout);
    

    This will probably cause an ioexception, so you have to catch it. The exception is not a bad thing in itself. I'm omitting some declarations (i.e. finals) so the anonymous class can access your variables. If not, then create a POJO that maintains a reference and pass that to the timertask

提交回复
热议问题