繁体   English   中英

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

[英]Checking internet connection on WIFI hotspot

我想检查设备是否与Internet真正连接,甚至连接到需要登录的打开的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”。

该怎么办?

从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