【问题标题】:Checking internet connection on WIFI hotspot检查 WIFI 热点上的互联网连接
【发布时间】:2014-02-13 05:28:54
【问题描述】:

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

怎么办?

【问题讨论】:

  • 使用setFollowRedirects(false)查看行为developer.android.com/reference/java/net/…
  • 如果我这样做,热点不会重定向我,然后我将无法看到我不在预期的主机上,对吗?那么我想它没有帮助。
  • 哦,你是对的。在深入挖掘之前,请尝试 requestRouteToHost 方法stackoverflow.com/questions/6923253/…
  • requestRouteToHost 会返回 true,即使我无法通过浏览器登录 Internet(例如)...

标签: android networking


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-02-02
    • 1970-01-01
    • 2015-01-02
    • 2016-06-21
    • 1970-01-01
    • 2021-10-30
    • 2012-05-18
    • 1970-01-01
    • 2012-02-21
    相关资源
    最近更新 更多