2014-02-11 46 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地址,而不是主機。這樣,如果有任何例外情況發生,您將確保這不是問題。