2014-07-26 56 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);