2014-02-11 27 views
0

我有以下代码来检查服务器的可用性,但它不工作 我一直在使用连接管理器效果很好如何检查服务器可用性的Android

public static boolean isConnected(Context context, String url){ 
    ConnectivityManager connectivityManager=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    if(connectivityManager!=null){ 

     if ((connectivityManager.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED) 
        ||(connectivityManager.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING) 
        ||(connectivityManager.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING) 
        ||(connectivityManager.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED)) 
      { 


        try{ 
         URL myUrl = new URL(url); 
         URLConnection connection = myUrl.openConnection(); 
         connection.setConnectTimeout(5000); 
         connection.connect(); 
         return true; 
        } catch (Exception e) { 
         // Handle your exceptions 
         return false; 
        } 



      } 

    } 
    return false; 

} 
+0

您的**代码在哪里检查服务器可用性**? –

+0

内部尝试并捕获 – HemangNirmal

+0

您可以通过提出请求来检查服务器的可用性。如果你在超时时间内得到响应(检查响应长度),那么你的服务器可用,如果没有,那么服务器失败。这就是 –

回答

1

检查网络可用性,你可以这样做:

  HttpParams httpParams = new BasicHttpParams(); 
     //int some_reasonable_timeout = (int) (30 * DateUtils.SECOND_IN_MILLIS); 
     int some_reasonable_timeout = 10; 
     HttpConnectionParams.setConnectionTimeout(httpParams, some_reasonable_timeout); 
     HttpConnectionParams.setSoTimeout(httpParams, some_reasonable_timeout); 
     //DefaultHttpClient client = new DefaultHttpClient(); 

     // get the response 
     HttpResponse response = null; 
     try { 
      response = client.execute(request); 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     StatusLine status = response.getStatusLine(); 
     Log.d("tag","status is"+status.toString()); 
      if (status.getStatusCode() == HttpStatus.SC_OK) 
      { 
      //cserver is available 
      } 
      else 
      { 
       //server is not available 
      } 
2

有很多方法。但我选择这个way.You可以实现像下面:

HttpClient httpclient = new DefaultHttpClient(); 
    String response = null; 
    URI url; 
    try { 

     String s = "url"; 

     url = new URI(s.replace(" ", "%20")); 

     Log.e("my webservice", "My webservice : " + url); 

     HttpGet httpget = new HttpGet(url); 
     HttpResponse httpResponse = null; 

     HttpParams httpParameters = new BasicHttpParams(); 
     // Set the timeout in milliseconds until a connection is 
     // established. 
     // The default value is zero, that means the timeout is not used. 
     int timeoutConnection = 3000; 
     HttpConnectionParams.setConnectionTimeout(httpParameters, 
       timeoutConnection); 
     // Set the default socket timeout (SO_TIMEOUT) 
     // in milliseconds which is the timeout for waiting for data. 
     int timeoutSocket = 5000; 
     HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 


     DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); 

     // Execute HTTP Post Request 
     httpResponse = httpClient.execute(httpget); 

     response = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); 
      Log.e("Login service", "resonse length : " + url); 


      if(response.length()>0){ 
       return true;//server available 
      }else{ 
       return false;//server not available 
      } 

      // this is what we extended for the getting the response string 
      // which we going to parese for out use in database // 


    } catch (Exception e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 
    return false; 
+0

感谢您的指导 – HemangNirmal

0

您可以简单地声明Socket。我在我的许多项目中使用了以下代码,并且超时确实可行。

Socket socket; 
final String host = "your.server.IP.or.host"; 
final int port = 80; 
final int timeout = 30000; // 30 seconds 

try { 
    socket = new Socket(); 
    socket.connect(new InetSocketAddress(host, port), timeout); 
} 
catch (UnknownHostException uhe) { 
    Log.e("ServerSock", "I couldn't resolve the host you've provided!"); 
} 
catch (SocketTimeoutException ste) { 
    Log.e("ServerSock", "After a reasonable amount of time, I'm not able to connect, Server is probably down!"); 
} 
catch (IOException ioe) { 
    Log.e("ServerSock", "Hmmm... Sudden disconnection, probably you should start again!"); 
} 

虽然这可能会很棘手。正确地在UnknownHostException之间,超时可能需要更长的时间,大约45秒 - 但另一方面,当无法解析主机时,通常会发生这种情况,因此这更像是意味着您的Internet访问配置了DNS配置错误(这是不太可能)。

无论如何,如果你想对冲你的赌注,你可以简单地使用你的IP地址,而不是主机。这样,如果有任何例外情况发生,您将确保这不是问题。