从URL java中读取

我正在尝试在java中读取URL,只要在浏览器中加载URL,它就可以正常工作。

但是如果它只是在浏览器中循环而在我尝试在浏览器中打开它时没有加载该页面,我的Java应用程序就会挂起,它可能会在给定足够时间的情况下永远等待。 如果加载超过20秒我停止我的应用程序,如何设置超时?

我正在使用URL

以下是代码的相关部分:

URL url = null; String inputLine; try { url = new URL(surl); } catch (MalformedURLException e) { e.printStackTrace(); } BufferedReader in; try { in = new BufferedReader(new InputStreamReader(url.openStream())); while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } catch (IOException e) { e.printStackTrace(); } 

我不知道你是如何使用URL类的。 如果发布一个片段会更好。 但这是一种适合我的方式。 看看它对你的情况有帮助:

  URL url = new URL(urlPath); URLConnection con = url.openConnection(); con.setConnectTimeout(connectTimeout); con.setReadTimeout(readTimeout); InputStream in = con.getInputStream(); 

URL#openStream方法实际上只是openConnection().getInputStream()的快捷方式。 以下是URL类的代码:

 public final InputStream openStream() throws java.io.IOException { return openConnection().getInputStream(); } 
  • 您可以按如下方式调整客户端代码中的设置:

     URLConnection conn = url.openConnection(); // setting timeouts conn.setConnectTimeout(connectTimeoutinMilliseconds); conn.setReadTimeout(readTimeoutinMilliseconds); InputStream in = conn.getInputStream(); 

参考: URLConnection#setReadTimeout , URLConnection#setConnectTimeout

  • 或者,您应将sun.net.client.defaultConnectTimeoutsun.net.client.defaultReadTimeout 系统属性设置为合理的值。

如果您使用URLConnection (或HttpURLConnection )来“从URL中读取”,那么您可以使用setReadTimeout()方法来控制它。

发布代码后编辑:

 URL url = null; String inputLine; try { url = new URL(surl); } catch (MalformedURLException e) { e.printStackTrace(); } BufferedReader in; try { URLConnection con = url.openConnection(); con.setReadTimeout( 1000 ); //1 second in = new BufferedReader(new InputStreamReader(con.getInputStream())); while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } catch (IOException e) { e.printStackTrace(); }