我想检查设备是否与互联网有真正的连接,甚至连接到需要登录的已打开的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"。
怎么办?
答案 0 :(得分:5)
来自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();
}
}