I am using the following code to check internet connectivity:
try {
HttpURLConnection httpConnection = (HttpURLConnection) (new URL("http://clients3.google.com/generate_204").openConnection());
httpConnection.setRequestProperty("User-Agent", "Test");
httpConnection.setRequestProperty("Connection", "close");
httpConnection.setConnectTimeout(15000);
httpConnection.connect();
if (httpConnection.getResponseCode() == 204 && httpConnection.getContentLength() == 0){
//internet is avialable
return;
}else{
Log.e(TAG, "Internet connection error: " + httpConnection.getResponseCode()
+ ": " + httpConnection.getResponseMessage());
}
} catch (IOException e) {
Log.e(TAG, "Internet connection error: " + e);
}
And i am getting the following response : code: 204 message: No Content
but content length is greater than 0 and hence it fails. Could some one please help me understand what is going on?
Thanks, Sunny
according to the title you want to ping google, but you are requesting an Site via HTTP, and these two things are not the same. So if you want to ping in Android visit this post: How to Ping External IP from Java Android
If you trust your Android device then you could just use this method:
}
But if you want to do it on your own then you should use the ping method because it requires less resources than an HTTP Request
The method above basically askes the android system if you have internet and if you ping google then you just do it on your own