简体   繁体   English

检查WIFI热点上的互联网连接

[英]Checking internet connection on WIFI hotspot

I'd like to check if the device has a real connection to the Internet, even connected to an opened wifi hotspot which requires log in. 我想检查设备是否与Internet真正连接,甚至连接到需要登录的打开的wifi热点。
The classic code : 经典代码:

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

works fine to see the device connected, but not really Internet. 可以正常运行,以查看已连接的设备,但实际上不能上网。

I use : 我用 :

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
    }

because when connected on a hotspot, we are usually redirected to a login page. 因为当连接到热点时,我们通常会重定向到登录页面。 Though, here on my test the httpUrlConnection isn't redirected and then urlConnection.getURL.getHost() is really "google.com". 不过,在我的测试中,httpUrlConnection不会被重定向,然后urlConnection.getURL.getHost()实际上是“ google.com”。

What to do? 该怎么办?

Got from Android 4.0.1 android.net.wifi.WifiWatchdogStateMachine: 从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();
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM