2013-06-26 62 views
0

我正在查询一个服务器(我没有写)来获取网站的HTML,但服务器有一些错误,有时不会返回答案。我在我的方法中有一个问题,但需要多分钟时间才能完成,同时我的代码也陷入了僵局。错误发生在rd = new BufferedReader(new Input ... line。有没有办法使用计时器强制我的代码离开方法,如果服务器没有在一秒钟或两秒内返回答案?了这个错误每隔两百倍只有代码运行。用计时器强制断线停止

public String getHTML(String urlToRead) { 
    URL url; 
    HttpURLConnection conn; 
    BufferedReader rd; 
    String line; 
    String result = ""; 
    try { 
     url = new URL(urlToRead); 
     conn = (HttpURLConnection) url.openConnection(); 
     conn.setRequestMethod("GET"); 
     rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
     while ((line = rd.readLine()) != null) { 
      result += line; 
     } 
     rd.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return result; 
} 

回答

4

利用现有的超时方法,setConnectTimeout(int)setReadTimeout(int)

如果超时,一个java.net.SocketTimeoutException提高。


无关紧要,但考虑不要抓住Exception

+0

+1不知道那些... –

0

你可以把代码放在不同的线程中。在开始线程之后,执行sleep,直到线程中的标志被设置,或者直到x秒过去。然后你继续执行主程序。