在Java中,是否有一个标准库可以检查网站的状态,即网站是否可以访问?
如果没有,是否有任何第三方库可以做同样的事情?
最佳答案
您可以执行以下操作,您会收到 200
的响应,即可访问,否则不可访问
public static boolean isAccessable(String url, int timeout) {
url = url.replaceFirst("https", "http"); // Otherwise an exception may
// be thrown on invalid SSL
// certificates.
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url)
.openConnection();
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
connection.setRequestMethod("HEAD");
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
return false;
}
} catch (IOException exception) {
return false;
}
return true;
}
关于java - 用Java检查网站的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13778635/