如何检查android apache连接的连接超时

时间:2014-07-26 14:04:48

标签: android

我正在做什么 ::我正在使用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;
    }

1 个答案:

答案 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);