Java: Internet connectivity check via ping to goog

2019-09-17 08:22发布

问题:

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

回答1:

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



回答2:

If you trust your Android device then you could just use this method:

public boolean isOnline() {
ConnectivityManager cm =
    (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
    return true;
}
return false;

}

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



回答3:

public Boolean isOnline() {
    try {
        Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
        int returnVal = p1.waitFor();
        boolean reachable = (returnVal==0);
        return reachable;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}