0

我正在尝试通过以下代码检查主机的可重复性:

 Socket socket = new Socket();

     try 
     {
         SocketAddress socketAddress = new InetSocketAddress(InetAddress.getByName("https://www.google.co.in"), 80);
         socket.connect(socketAddress, 2000);
     }
     catch (IOException e) 
     {
        Log.e("server",e.getMessage());
         return false;
     }
     finally 
     {
         if (socket.isConnected()) {
             try {
                socket.close();
             }
             catch (IOException e) {
                 e.printStackTrace();
             }
         }
    }
     return true;

但它总是返回假。还有什么需要补充的吗?它给出了未解决的主机 url 异常。

4

1 回答 1

0

试试这个:

public static boolean ping(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;
    }
}

有了这个,你正在 ping 一个网站,比如谷歌,所以你可以检查可达性。

于 2014-07-14T17:19:59.710 回答