HttpURLConnection 超时设置

2022-08-31 08:05:25

如果URL需要超过5秒的时间来连接,我想返回false - 使用Java怎么可能?这是我用来检查URL是否有效的代码

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

答案 1

HttpURLConnection具有 setConnectTimeout 方法。

只需将超时设置为 5000 毫秒,然后捕获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;
}



答案 2

您可以像这样设置超时,

con.setConnectTimeout(connectTimeout);
con.setReadTimeout(socketTimeout);