我需要一个监视器类来定期检查给定的 HTTP URL 是否可用。我可以使用 Spring TaskExecutor 抽象来处理“定期”部分,所以这不是这里的主题。问题是:在 java 中 ping URL 的首选方法是什么?
这是我当前的代码作为起点:
try {
final URLConnection connection = new URL(url).openConnection();
connection.connect();
LOG.info("Service " + url + " available, yeah!");
available = true;
} catch (final MalformedURLException e) {
throw new IllegalStateException("Bad URL: " + url, e);
} catch (final IOException e) {
LOG.info("Service " + url + " unavailable, oh no!", e);
available = false;
}
- 这有什么好处(它会做我想要的)吗?
- 我必须以某种方式关闭连接吗?
- 我想这是一个
GET
请求。有没有办法发送HEAD
代替?
最佳答案
Is this any good at all (will it do what I want?)
你可以这样做。另一种可行的方法是使用 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.
}
}
boolean reachable = InetAddress.getByName(hostname).isReachable();
但是,这并没有明确测试端口 80。由于防火墙阻止了其他端口,您可能会收到误报。
Do I have to somehow close the connection?
不,您没有明确需要。它在后台处理和汇集。
I suppose this is a GET request. Is there a way to send HEAD instead?
您可以将获取的URLConnection
转换为HttpURLConnection
然后使用 setRequestMethod()
设置请求方法。但是,您需要考虑到一些糟糕的 web 应用程序或本地服务器可能会返回 HTTP 405 error对于 HEAD(即不可用、未实现、不允许),而 GET 工作得非常好。如果您打算验证链接/资源而不是域/主机,则使用 GET 更可靠。
Testing the server for availability is not enough in my case, I need to test the URL (the webapp may not be deployed)
确实,连接主机只通知主机是否可用,而不是内容是否可用。如果 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 section 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;
}
}
关于java - ping HTTP URL 以确保可用性的首选 Java 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3584210/