通过http判断网络是否可用

一个工具类;

代码如下:


import android.util.Log;

import java.net.HttpURLConnection;
import java.net.URL;

/**
 *  网络判断工具类
 * @desc : 网络判断
 */
public class NetworkUtils {

    /**
     * 判断是否有网络.
     */
    public static boolean isNetworkAvailable() {
        // Android 4.0 之后不能在主线程中请求HTTP请求
        int counts = 0;
        boolean isNetsOnline = true;
        HttpURLConnection con = null;
        while (counts < 2) {
            try {
                URL url = new URL("https://www.baidu.com");
                con = (HttpURLConnection) url.openConnection();
                con.setReadTimeout(10000);
                int state = con.getResponseCode();
                Log.e("FragmentNet", "isNetOnline counts: " + counts + "=state: " + state);
                if (state == 200) {
                    isNetsOnline = true;
                }
                con.disconnect();
                break;
            } catch (Exception ex) {
                isNetsOnline = false;
                counts++;
                if (con != null) {
                    con.disconnect();
                }
                Log.e("FragmentNet", "isNetOnline URL不可用,连接第 " + counts + " 次");
            }
        }
        return isNetsOnline;
    }

}

在此做个笔记

你可能感兴趣的:(http,https,android,java,开发语言)