检查Android中的Internet连接(非连接状态)

时间:2014-06-27 15:41:04

标签: android http-post httprequest http-get

我需要帮助来检查是否存在与某个指定网址的连接,以确保我已连接到互联网。

我用过这段代码:

private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

但它没那么有用,因为该设备可能连接到WiFi或移动网络,但没有连接到互联网。

请帮忙

1 个答案:

答案 0 :(得分:1)

您可以ping网站以检查互联网是否可用。您可以ping google.com,主要是在线。

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;
    }
}

取自Preferred Java way to ping an HTTP URL for availability