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();
精彩评论