監控 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中文網其他相關文章!