HttpURLConnection超时设置 [英] HttpURLConnection timeout settings

查看:149
本文介绍了HttpURLConnection超时设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果URL连接超过5秒,我想返回false - 使用Java可以实现这一点吗?以下是我用来检查URL是否有效的代码

I want to return false if the URL takes more then 5 seconds to connect - how is this possible using Java? Here is the code I am using to check if the URL is valid

HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);


推荐答案

HttpURLConnection setConnectTimeout 方法。

只需将超时设置为5000毫秒,然后捕获 java.net.SocketTimeoutException

Just set the timeout to 5000 milliseconds, and then catch java.net.SocketTimeoutException

您的代码应如下所示:



try {
   HttpURLConnection.setFollowRedirects(false);
   HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
   con.setRequestMethod("HEAD");

   con.setConnectTimeout(5000); //set timeout to 5 seconds

   return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
   return false;
} catch (java.io.IOException e) {
   return false;
}


这篇关于HttpURLConnection超时设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆