java - HttpURLConnection超时设置

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

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


最佳答案:

HttpURLConnection有一个setConnectTimeout方法。
只需将超时设置为5000毫秒,然后catchjava.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; }