从 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();
}
I'm trying to read URL in java, and it works as long as the URL is loading in browser.
But if it is just cylcing in the browser and not loading that page when I'm trying to open it in my browser, my java app just hangs, it will probably wait forever given enough time. How do I set timeout on that or something, if its loading for more than 20 seconds that I stop my application?
I'm using URL
Here is a relevant part of the code :
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不知道你如何使用 URL 类。如果贴个片段就更好了。但这是一种对我有用的方法。看看它对您的情况是否有帮助:
I don't know how u are using the URL class. It would have been better if post a snippet. But here is a way that works for me. See if it helps in your case:
URL#openStream 方法实际上只是
openConnection().getInputStream()
的快捷方式。以下是 URL 类的代码:您可以按如下方式调整客户端代码中的设置:
参考:URLConnection#setReadTimeout, URLConnection#setConnectTimeout
sun.net.client.defaultConnectTimeout
和sun.net.client.defaultReadTimeout
系统属性设置为合理的值。The URL#openStream method is actually just a shortcut for
openConnection().getInputStream()
. Here is the code from the URL class:You can adjust settings in the client code as follows:
Reference: URLConnection#setReadTimeout, URLConnection#setConnectTimeout
sun.net.client.defaultConnectTimeout
andsun.net.client.defaultReadTimeout
system property to a reasonable value.如果您使用
URLConnection
(或HttpURLConnection
)“从 url 读取”,您可以使用setReadTimeout()
方法来控制那。发布代码后进行编辑:
If you are using a
URLConnection
(orHttpURLConnection
) to "read from a url" you have asetReadTimeout()
method which allows you to control that.Edited after you posted the code:
您应该在 AndroidMenifest.xml 中添加互联网权限
并将其添加到 main 函数中:
You should add internet permission in AndroidMenifest.xml
and add it in the main function: