这有什么好处吗(它会做我想要的吗?)
你可以这样做。另一种可行的方法是使用java.net.Socket
.
public static boolean pingHost(String host, int port, int timeout) {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port), timeout);
return true;
} catch (IOException e) {
return false; // Either timeout or unreachable or failed DNS lookup.
}
}
还有InetAddress#isReachable()
:
boolean reachable = InetAddress.getByName(hostname).isReachable();
但是,这并没有明确测试端口 80。由于防火墙阻止了其他端口,您可能会遇到误报。
我是否必须以某种方式关闭连接?
不,您没有明确需要。它在引擎盖下被处理和汇集。
我想这是一个 GET 请求。有没有办法发送 HEAD 代替?
您可以将获得的内容URLConnection
转换为HttpURLConnection
然后用于setRequestMethod()
设置请求方法。但是,您需要考虑到一些糟糕的 web 应用程序或本地服务器可能会为 HEAD 返回HTTP 405 错误(即不可用、未实现、不允许),而 GET 工作正常。如果您打算验证链接/资源而不是域/主机,则使用 GET 更可靠。
在我的情况下测试服务器的可用性是不够的,我需要测试 URL(可能没有部署 webapp)
实际上,连接主机只通知主机是否可用,而不是内容是否可用。如果 web 服务器启动时没有问题,但 web 应用程序在服务器启动期间无法部署,这也是一件好事。然而,这通常不会导致整个服务器停机。您可以通过检查 HTTP 响应代码是否为 200 来确定。
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("HEAD");
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
// Not OK.
}
// < 100 is undetermined.
// 1nn is informal (shouldn't happen on a GET/HEAD)
// 2nn is success
// 3nn is redirect
// 4nn is client error
// 5nn is server error
有关响应状态代码的更多详细信息,请参阅RFC 2616 第 10 节。connect()
如果您正在确定响应数据,则不需要调用。它将隐式连接。
为了将来参考,这里有一个实用方法的完整示例,还考虑了超时:
/**
* Pings a HTTP URL. This effectively sends a HEAD request and returns <code>true</code> if the response code is in
* the 200-399 range.
* @param url The HTTP URL to be pinged.
* @param timeout The timeout in millis for both the connection timeout and the response read timeout. Note that
* the total timeout is effectively two times the given timeout.
* @return <code>true</code> if the given HTTP URL has returned response code 200-399 on a HEAD request within the
* given timeout, otherwise <code>false</code>.
*/
public static boolean pingURL(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();
return (200 <= responseCode && responseCode <= 399);
} catch (IOException exception) {
return false;
}
}