這是任何好處都沒有(將它做我想要什麼?)
你可以這樣做。另一種可行的方法是使用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()
設置請求方法。但是,您需要考慮到一些糟糕的webapps或本地服務器可能會返回HTTP 405 error作爲HEAD(即不可用,未實現,不允許),而GET工作得很好。如果您打算驗證鏈接/資源而不是域/主機,則使用GET更可靠。
測試可用性的服務器是不夠的,在我的情況,我需要測試的URL(web應用程序可能不會部署)
事實上,連接主機僅通告如果主機可用,則不是如果內容可用。 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;
}
}
感謝您的詳細信息,這樣的答案是什麼讓SO成爲一個好地方。在我的情況下測試服務器的可用性是不夠的,我需要測試URL(可能不會部署webapp),所以我會堅持使用HttpURLConnection。關於HEAD不是一個好的測試:如果我知道目標URL支持HEAD,這是一個好方法,我會檢查它。 – 2010-08-27 13:09:06
如果這是功能要求,那麼'HttpURLConnection'是最好的方法。你也想確定響應代碼。你也可以使用'Socket'來做到這一點,但這隻會增加冗長並需要有關HTTP規範的知識。 – BalusC 2010-08-27 13:26:56
有可能獲得** java.io.IOException:在某些服務器上發生意外的流**結束,要修復它,您需要添加connection.setRequestProperty(「Accept-Encoding」, 「musixmatch」); 這是已知問題,並在[code.google.com](https://code.google.com/p/android/issues/detail?id=24672) – 2013-03-27 09:06:31