如何在提出请求之前检查互联网连接

时间:2015-01-10 11:27:05

标签: java android

我有这个通常的代码来向服务器发出HTTP请求。

      HttpClient httpclient = new DefaultHttpClient();
      ...
        HttpGet httpGet = new HttpGet(finalUri.toURI());
        httpGet.addHeader("Accept", "text/xml");

        response = httpclient.execute(httpGet);

当有互联网连接时,此功能正常。但是当没有互联网连接时,代码只会在httpclient.execute(httpGet);等待很长时间,直到它超时并抛出异常并导致应用程序崩溃。

01-10 15:17:48.612  20692-20806/com.somepackage.somepackage  E/EXCEPTION﹕ Unable to resolve host "myapi.myhost.com": No address associated with hostname

对于异常,我可以捕获UnknownHostException e并处理它。但仍然有办法预先知道互联网连接丢失了吗?

5 个答案:

答案 0 :(得分:1)

您可以使用 NetworkInfo 来实现此目的。

private boolean checkNetworkConnection() {
    NetworkInfo networkInfo = ((ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
    if (networkInfo == null || !networkInfo.isConnected()) {
        return false;
    } else {
        return true;
    }
}

答案 1 :(得分:0)

这适合我。

public boolean IsInternetAvailable(Context context)
{

    ConnectivityManager connectivityManager 
            = (ConnectivityManager) (context.getSystemService(Context.CONNECTIVITY_SERVICE));
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

答案 2 :(得分:0)

使用连接类型检查互联网连接状态的另一种方法:

public boolean getConnectionStatus(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
if (conn == NetworkUtil.TYPE_WIFI||conn == NetworkUtil.TYPE_MOBILE) {
  return true;
} 
else{
   return false
}

}

答案 3 :(得分:0)

我建议您查看以下内容。您可以通过标准java.net.URLConnection课程查看。

 try{
     URLConnection urlConnection = finalUri.openConnection();
     urlConnection.connect();
 }
 catch(Exception ex){
    //No connection to finalUri
    // return your error code for no connection
 }

答案 4 :(得分:0)

在当前ActivityFragment

中添加新方法
private boolean isNetworkAvailable(){
        boolean available = false;
        /** Getting the system's connectivity service */
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        /** Getting active network interface  to get the network's status */
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        if(networkInfo !=null && networkInfo.isAvailable())
            available = true;

        /** Returning the status of the network */
        return available;
    }

以下是如何使用它。您可以在onCreate()方法中使用它:

if (isNetworkAvailable() == true){ // if network is available
   // do your thing here
   ...
}else{ // "else" means that the network is not available
   // do your thing here
   ...
}