java - ping HTTP URL 以确保可用性的首选 Java 方法

标签 java http url ping

我需要一个监视器类来定期检查给定的 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;
}
  1. 这有什么好处(它会做我想要的)吗?
  2. 我必须以某种方式关闭连接吗?
  3. 我想这是一个 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.
    }
}

还有InetAddress#isReachable() :

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/

相关文章:

javascript - 在 React Router v4 中表示 URL 查询

java - 树莓派无法与ACR122U通信

java - 内存空间什么时候分配给变量?

java - 对使用公钥和私钥进行加密(用于加密)感到困惑

java - Reddit api Oauth : Server returned HTTP response code: 411 for URL error

javascript - 如何使用 Javascript 或 jQuery 从链接字符串中提取基本 URL?

java - 从 java 轮询 NFS 共享会破坏文件系统

javascript - 如何作为客户端连接 Node.js 和 Android?

node.js - Nodejs 异常转义 try/catch block

Javascript 图片网址验证