简体   繁体   中英

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.
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".

What to do?

Got from 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();
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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