2013-12-18 55 views
2

我已经写了这段非常经典的代码来读取URL的内容。Java,限制BufferedReader的读取时间

// Prepares the connection 
URL url = new URL(urlString); 
URLConnection uc = url.openConnection(); 

// Reads the data 
StringBuilder data; 
String inputLine; 
try (InputStreamReader isr = new InputStreamReader(uc.getInputStream(), "utf-8"); 
    BufferedReader in = new BufferedReader(isr)) { 
    data = new StringBuilder(); 
    while ((inputLine = in.readLine()) != null) { 
     data.append(inputLine); 
    } 
} 

// Returns the read data 
return data.toString(); 

但有时候,我在看的URL中包含太多的数据,或者客户端的连接速度太慢,或任何...等读取花费太多时间。

有没有办法指定BufferedReader(或者InputStreamReader,或者URLConnection?)“max-reading-time”?理想情况下,它将在“达到最大阅读时间”后发出TimeoutException。

我做了一些研究,但我所能找到的只是对接收数据大小的限制,而不是执行时间。

回答

3

在开始阅读之前,请致电URLConnection.setReadTimeout()。如果超时过期,将会抛出SocketTimeoutException

+0

出于好奇,你知道这是如何实现的吗? –

+0

@SotiriosDelimanolis使用Socket.setSoTimeout(),当然,在网络URL的情况下。对其他网址没有任何作用。 – EJP

+0

这是超时完成本地? –

相关问题