监控 HTTP URL 的可用性对于维护系统完整性和用户满意度至关重要。实现此目的的首选 Java 方法是本文讨论的主题。
提供的代码片段尝试使用 URLConnection 对象 ping HTTP URL。它可以正常工作,但会引起一些问题:
使用 Java.net.Socket:
<code class="java">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; } }</code>
使用 InetAddress.isReachable():
<code class="java">boolean reachable = InetAddress.getByName(hostname).isReachable();</code>
但是,此方法不会显式测试端口 80,由于防火墙限制,存在漏报的风险。
<code class="java">HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("HEAD"); int responseCode = connection.getResponseCode(); if (responseCode != 200) { // Not available }</code>
<code class="java">public static boolean pingURL(String url, int timeout) { url = url.replaceFirst("^https", "http"); // Handle SSL certificate issues 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; } }</code>
HttpURLConnection 对象自动处理连接池和关闭,无需显式清理.
以上是如何在 Java 中可靠地 Ping HTTP URL 以进行可用性监控?的详细内容。更多信息请关注PHP中文网其他相关文章!