user754740 user754740 - 1 year ago 133
Java Question

Download URL content with timeout

I want to download the URL content in java with a specified download time. For ex: i want to have a maximum download timeout of 10 seconds for If download takes more than 10s, then an error should be thrown. I have written the code for opening a connection and downloading the entire contents. But how do i set the download timeout? Here is the code snippet:

StringBuilder text = new StringBuilder();

urlconn = (HttpURLConnection)url.openConnection();
buf = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
while((line = buf.readLine()) != null)
System.out.println(url + "=> "+ urlconn.getResponseCode());

Answer Source

You can set it by URLConnection#setReadTimeout().

urlconn.setReadTimeout(10000); // 10 sec
// ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download