2

我想检查设备是否真正连接到互联网,甚至连接到需要登录的打开的 wifi 热点。
经典代码:

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected() && netInfo.isAvailable(){
   //connection on
}

可以正常查看设备已连接,但不是真正的互联网。

我用 :

URL url = new URL("http://www.google.com");
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setConnectTimeout((int)(1000 * TIMEOUT)); 
                urlConnection.connect();
                if (urlConnection.getResponseCode() == 200 && url.getHost().equals(urlConnection.getURL().getHost())) {
       //I am supposed to be connected
    }

因为当连接到热点时,我们通常会被重定向到登录页面。虽然,在我的测试中,httpUrlConnection 没有被重定向,然后 urlConnection.getURL.getHost() 真的是“google.com”。

该怎么办?

4

1 回答 1

5

从 Android 4.0.1 android.net.wifi.WifiWatchdogStateMachine 获得:

private boolean isConnected() {
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL("http://clients3.google.com/generate_204");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setInstanceFollowRedirects(false);
            urlConnection.setConnectTimeout(10000);
            urlConnection.setReadTimeout(10000);
            urlConnection.setUseCaches(false);
            urlConnection.getInputStream();
            return urlConnection.getResponseCode() == 204;
        } catch (IOException e) {
            log("Walled garden check - probably not a portal: exception " + e);
            return false;
        } finally {
            if (urlConnection != null) urlConnection.disconnect();
        }
}
于 2012-07-31T13:59:23.153 回答