2014-07-26 83 views
0

我在做什麼的異步任務使用此代碼 ::我檢查互聯網連接與timeout,它返回true如果連接可用回報false如果連接不可用如何檢查連接超時的Android阿帕奇連接

public static boolean hasActiveInternetConnection() { 
      try { 

       HttpClient Client = new DefaultHttpClient(); 

       HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection()); 
       urlc.setRequestProperty("User-Agent", "Test"); 
       urlc.setRequestProperty("Connection", "close"); 
       urlc.setConnectTimeout(500); 
       urlc.connect(); 
       return true; 
      } catch (IOException e) { 
       Log.e("Log", "Error checking internet connection", e); 
      } 
     return false; 
    } 

我如何可以做同樣爲Apache HTTP客戶端下面

public static String doConnection(String url) { 
     HttpGet httpget=null; 
     String mContent=null; 
     HttpClient Client=null; 

     Client = new DefaultHttpClient(); 
     httpget = new HttpGet(url); 
     ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
     mContent = Client.execute(httpget, responseHandler); 

     return mContent; 
    } 
+0

你就不能環繞與嘗試執行,做一樣的,你在第1部分的代碼做? – Simas

+0

@ user3249477 ......是的,我可以但我不知道如何給超時.... :( – Devrath

回答

0

請試試看:

HttpGet httpget=null; 
String mContent=null; 
HttpClient Client=null; 

Client = new DefaultHttpClient(); 
Client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 500); 
httpget = new HttpGet(url); 
ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
try { 
    mContent = Client.execute(httpget, responseHandler); 
    return true; 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
return false; 

報告錯誤,如果有的話。

編輯:這看起來比較清爽:

HttpParams params = new BasicHttpParams(); 
    HttpConnectionParams.setConnectionTimeout(params, 500); 

    Client = new DefaultHttpClient(params);