I have this code that downloads a web page:
HttpURLConnection connection;
private String downloadContent() {
InputStream content;
Source parser;
try {
content = connection.getInputStream(); //
parser = new Source(content);
content.close();
return parser.toString();
} catch (Exception e) {
return null;
}
}
While doing the download, I tried to get the amount of downloaded data, and if it reaches a limit, I stop the downloading, but I not found a way to do this. If someone know how to do, please tell me.
Now I want to limit the download time. Example: if the download pass 20 seconds, I stop it. I want to do this because my program it's an webcrawler and if by an error, it begins downloading a big file, it will stuck in the download, and is not this I want to do, so a filter in download by size is welcome, but as I don't know, a filter time will prevent this problem.
解决方案
The proper way to achieve this is the following:
public class TimeOut {
public static class MyJob implements Callable {
@Override
public String call() throws Exception {
// Do something
return "result";
}
}
public static void main(String[] args) {
Future control
= Executors.newSingleThreadExecutor().submit(new MyJob());
try {
String result = control.get(5, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
// 5 seconds expired, we cancel the job !!!
control.cancel(true);
}
catch (InterruptedException ex) {
} catch (ExecutionException ex) {
}
}
}