我正在做什么 ::我正在使用timeout
的异步任务中使用此代码检查互联网连接,如果连接可用则返回true
返回{{ 1}}如果连接不可用
false
我如何为apache Http客户端:
做同样的事情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;
}
答案 0 :(得分: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);