本文介绍了Java的:通过平互联网连接检查,以谷歌不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的code,检查互联网连接:

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

和我得到以下回应:
code:204
消息:没有内容

And i am getting the following response :code: 204message: No Content

,但内容长度大于0,因此它失败。
可能有人请帮助我明白是怎么回事呢?

but content length is greater than 0 and hence it fails.Could some one please help me understand what is going on?

谢谢,
阳光明媚

Thanks,Sunny

推荐答案

如果你信任你的Andr​​oid设备,那么你可以只使用此方法:

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;

}

但是,如果你想这样做你自己,那么你应该,因为它需要比HTTP请求的资源较少使用ping法

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

以上基本方法askes android系统,如果你有互联网,如果你谷歌平,那么你只需做你自己的

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

这篇关于Java的:通过平互联网连接检查,以谷歌不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 02:59