2011-11-15 54 views

回答

0

你可以有一個AsyncTask來ping服務器,並根據響應繼續。

使用類HttpURLConnection的

doInBackground(..) { 
    boolean success = false; 
    HttpURLConnection urlConnection; 
    URL url = new URL("http://www.android.com/"); 
    try { 
     urlConnection = (HttpURLConnection) url.openConnection(); 
    }catch(Exception e){ 
     Log.e(TAG,"OpenConnection call failed"); 
    } 
     success = true; 
    } 
    return success; 
} 
+0

上面的代碼只給出了'true',如果url =「http://www.unavailablereally.com/」或url =「http://www.android.com/」。如果我們有任何像「hp:」而不是「http」的變化,它會拋出異常。我們如何才能發現,如果「http://www.google.com/」表示可用,並且「http://www.unavailablereally.com/」表示服務器不可用的結果... –

0

您可以創建一個servlet /網頁或任何你感覺舒服,返回OK或錯誤取決於從Android服務器狀態的服務器上,你必須調用URL和檢查返回值,也對你的try/catch你必須看具體的異常,例如與超時有關,還檢查HTTP狀態如果您的HTTP請求返回200,然後是好的,你可以獲取從URL服務器狀態檢查http://developer.android.com/reference/java/net/HttpURLConnection.html

 `boolean isOK = false; 
     try { 
      URL url = new URL("http://yourserverurl/yourstatusmethod"); 
      HttpURLConnection urlcon = (HttpURLConnection) url.openConnection(); 
      urlcon.connect(); 
      if (urlcon.getResponseCode() == 200) { 
        InputStream in = new BufferedInputStream(urlConnection.getInputStream()); 
        String serverStatus = readStream(in); //assuming that "http://yourserverurl/yourstatusmethod" returns OK or ERROR depending on your server status check   
        isOK = (serverStatus.equalsIgnoreCase("OK")); 
      }else{ 
       isOK = false; 
      } 

      url.disconnect(); 

     } catch (MalformedURLException e1) { 
        isOK = false; 
        e1.printStackTrace(); 
     } catch (IOException e) { 
        isOK = false; 
        e.printStackTrace(); 
     } 

    the readStream is a method that convert inputstream to string 
    `public static String readStream (InputStream in) throws IOException { 
     StringBuffer out = new StringBuffer(); 
     byte[] b = new byte[4096]; 
     for (int n; (n = in.read(b)) != -1;) { 
      out.append(new String(b, 0, n)); 
     } return out.toString(); 
    }` 

this is just and idea.... there are a lot of ways to check server availability 
相關問題