1

How can I implement a 60 second timeout in this code?

This code is opening a URL, downloading plain text, and sending output as a string variable.

Works, but sometimes hangs, and I have to start all over again.

I was hoping something which would timeout after 60 seconds and return whatever data is retrieved.

Please don't suggest to use external libs like Apache etc. If I could edit this code itself, then that would be better.

public static String readURL( URL url )
{
  try
  {
    // open the url stream, wrap it an a few "readers"
    BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
    String s="";
    String line="";

    while ((line = reader.readLine()) != null)
    {
      s=s+"\r\n"+line;
    }

    reader.close();
    return s;
  }catch(Exception e){ StringWriter errors = new StringWriter(); e.printStackTrace(new PrintWriter(errors)); return errors.toString(); }

}//end method
Sumit Kumar
  • 761
  • 1
  • 6
  • 17

1 Answers1

-1
Thread.sleep(60000);

Above code will let the Thread sleep for 60 seconds, and do nothing during that time.

If you want to change the timeout of your connection; Look at Is it possible to read from a InputStream with a timeout?

sarcode
  • 160
  • 1
  • 9
  • Hi, Thread.sleep will hold the program. I don't want that. I want the program to keep running, but if no data is retrieved in 60 seconds, then method returns an empty String. I will look into that link you posted. Thanks – Sumit Kumar Aug 15 '18 at 15:25
  • Got it, this works good. int timeout = 60000; //60 seconds URLConnection con = url.openConnection(); con.setConnectTimeout( timeout ); con.setReadTimeout( timeout ); BufferedReader reader = new BufferedReader(new InputStreamReader( con.getInputStream() )); – Sumit Kumar Aug 15 '18 at 21:35