Android 检查WIFI热点上的internet连接
我想检查设备是否真正连接到互联网,甚至连接到需要登录的已打开wifi热点。Android 检查WIFI热点上的internet连接,android,networking,Android,Networking,我想检查设备是否真正连接到互联网,甚至连接到需要登录的已打开wifi热点。 经典代码: ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected() &&
经典代码:
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected() && netInfo.isAvailable(){
//connection on
}
可以很好地看到设备已连接,但不是真正的Internet
我使用:
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();
}
}
使用
setFollowRedirects(false)
查看行为如果我这样做,热点将不会重定向我,然后我将无法看到我不在预期的主机上,对吗?那我想这没用。哦,你说得对。在进一步挖掘之前,请尝试requestRouteToHost方法requestRouteToHost返回true,即使我无法通过浏览器登录到Internet(例如)。。。