How to “time out” functions in Java?

private String indexPage(URL currentPage) throws IOException {
private String indexPage(URL currentPage) throws IOException {
    String content = "";
    is = currentPage.openStream();
    content = new Scanner( is ).useDelimiter( "\\Z" ).next();
    return content;
}

This is the function that I am currently crawling the web page Function of the problem:

content = new Scanner( is ).useDelimiter( "\\Z" ).next();

If the page doesn't answer or takes a long time to answer, my topic will hang on the top line If it takes more than 5 seconds to load the stream completely, what is the easiest way to abort this function?

Thank you in advance!

Solution

If you enable connection and read timeouts on a network connection instead of using a separate observer thread alone, it may be sufficient (although it does not fully meet your requirements), for example:

URL url = new URL("...");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(10000);
InputStream is = conn.getInputStream();

If it takes more than 5 seconds (5000 milliseconds) to connect to the server, or if you have to wait more than 10 seconds (10000 milliseconds) between any content blocks actually read, this example will fail However, it does not limit the total time you need to retrieve a page

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>