阅读:2715回复:0

一个java检测能否连接google.com高效方法

楼主#
更多 发布于:2021-05-14 01:36


public static boolean pingGoogle() {
    Future<Boolean> callableFuture  = Executors.newSingleThreadExecutor().submit(new Callable<Boolean>() { @Override public Boolean call() throws IOException {
                HttpURLConnection urlc = (HttpURLConnection) (new URL( "http://www.google.com").openConnection()); urlc.setRequestProperty("User-Agent", "Test"); urlc.setRequestProperty("Connection", "close"); urlc.setConnectTimeout(1000); urlc.setReadTimeout(1000); urlc.connect(); return (urlc.getResponseCode() == 200); }
    }); try { return callableFuture.get(); } catch (ExecutionException | InterruptedException e) {
        e.printStackTrace(); return false; }
}


new Thread(new Runnable() { @Override public void run() { if (!pingGoogle()) {
            runOnUiThread(new Runnable() { @Override public void run() {
                    Toast.makeText(MainActivity.this, "无法连接google!", Toast.LENGTH_SHORT).show(); }
            }); }
    }
}).start();
尝试用ping来做,很耗时,还是这个效率高。

最新喜欢:

zhaoyf13zhaoyf...
游客

返回顶部