下载URL内容超时
我想用java来下载指定下载时间的URL内容。例如:我希望 www.yahoo.com 的最大下载超时时间为 10 秒。如果下载时间超过 10 秒,则应抛出错误。我已经编写了用于打开连接并下载全部内容的代码。但是如何设置下载超时呢?这是代码片段:
StringBuilder text = new StringBuilder();
urlconn = (HttpURLConnection)url.openConnection();
urlconn.setConnectTimeout(100000);
//urlconn.setInstanceFollowRedirects(false);
urlconn.setRequestMethod("GET");
urlconn.connect();
buf = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
while((line = buf.readLine()) != null)
text.append(line);
System.out.println(url + "=> "+ urlconn.getResponseCode());
I want to download the URL content in java with a specified download time. For ex: i want to have a maximum download timeout of 10 seconds for www.yahoo.com. If download takes more than 10s, then an error should be thrown. I have written the code for opening a connection and downloading the entire contents. But how do i set the download timeout? Here is the code snippet:
StringBuilder text = new StringBuilder();
urlconn = (HttpURLConnection)url.openConnection();
urlconn.setConnectTimeout(100000);
//urlconn.setInstanceFollowRedirects(false);
urlconn.setRequestMethod("GET");
urlconn.connect();
buf = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
while((line = buf.readLine()) != null)
text.append(line);
System.out.println(url + "=> "+ urlconn.getResponseCode());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
URLConnection.setReadTimeOut ()
。Use
URLConnection.setReadTimeOut()
.您可以通过
URLConnection#setReadTimeout()
。You can set it by
URLConnection#setReadTimeout()
.