167

我需要一个监视器类来定期检查给定的 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代替发送?
4

6 回答 6

282

这有什么好处吗(它会做我想要的吗?)

你可以这样做。另一种可行的方法是使用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;
    }
}
于 2010-08-27T12:56:41.610 回答
17

通过在 URL 对象上调用 openConnection()而不是使用 URLConnection 使用HttpURLConnection

然后使用getResponseCode()将在您从连接中读取后为您提供 HTTP 响应。

这是代码:

    HttpURLConnection connection = null;
    try {
        URL u = new URL("http://www.google.com/");
        connection = (HttpURLConnection) u.openConnection();
        connection.setRequestMethod("HEAD");
        int code = connection.getResponseCode();
        System.out.println("" + code);
        // You can determine on HTTP return code received. 200 is success.
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

还要检查类似的问题How to check if a URL exists or return 404 with Java?

希望这可以帮助。

于 2010-08-27T13:00:04.410 回答
8

您也可以使用HttpURLConnection,它允许您设置请求方法(HEAD例如)。 这是一个示例,展示了如何发送请求、读取响应和断开连接。

于 2010-08-27T12:48:15.777 回答
4

以下代码执行HEAD请求以检查网站是否可用。

public static boolean isReachable(String targetUrl) throws IOException
{
    HttpURLConnection httpUrlConnection = (HttpURLConnection) new URL(
            targetUrl).openConnection();
    httpUrlConnection.setRequestMethod("HEAD");

    try
    {
        int responseCode = httpUrlConnection.getResponseCode();

        return responseCode == HttpURLConnection.HTTP_OK;
    } catch (UnknownHostException noInternetConnection)
    {
        return false;
    }
}
于 2015-04-04T14:37:59.700 回答
4
public boolean isOnline() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int     exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    } catch (IOException | InterruptedException e) { e.printStackTrace(); }
    return false;
}

可能的问题

  • 这真的足够快吗?是的,非常快!
  • 我不能只 ping 我自己的页面吗?无论如何我都想请求它?当然!如果您想区分“可用的互联网连接”和您自己的服务器是否可以访问,您甚至可以同时检查两者 如果 DNS 出现故障怎么办?Google DNS(例如 8.8.8.8)是世界上最大的公共 DNS 服务。截至 2013 年,它每天处理 1300 亿次请求。让我们说,您的应用程序没有响应可能不会成为今天的话题。

阅读链接。它看起来很好

编辑:在我使用它的经验中,它不如这种方法快:

public boolean isOnline() {
    NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

它们有点不同,但在仅检查互联网连接的功能中,由于连接变量,第一种方法可能会变慢。

于 2017-08-29T12:47:35.393 回答
2

考虑使用 Restlet 框架,它对这类事情有很好的语义。它功能强大且灵活。

代码可以很简单:

Client client = new Client(Protocol.HTTP);
Response response = client.get(url);
if (response.getStatus().isError()) {
    // uh oh!
}
于 2010-08-27T13:36:55.660 回答