开发者

Handle timeout when reading a remote file

I am reading a remote file(xml) that is rendered by a webserver on the fly.Sometimes the webserver takes tim开发者_运维百科e to render the remote file. Sometime there is issue with netowrk and remote url is not reachable Am using the following code:

URL url = new URL(myurl);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
String strOutput = "";
System.out.println("start now");
//my code hangs after  priting start now    sometime.
//i think in.ready blocks the code flow.
if(in.ready() ){         
  while ((inputLine = in.readLine()) != null) {
       strOutput = strOutput + inputLine;
  }
}

If input stream is not ready i want my code to continue withoud blocking.How can i handle it?

How can i make sure that my code flow is never blocked indefinately?


You can set time out on the URL connection. See javadocs.

But you will have to get your stream slightly differently:

URLConnection con = url.openConnection();
con.setReadTimeout(timeout);
InputStream in = con.getInputStream();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜