AsyncTask接口,网络请求,方法类

public class HttpUtils {
    public static boolean isWork(Context context){
        if(context!=null){
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            if(info!=null){
                return info.isAvailable();
            }
        }
        return false;
    }

    public static void httpAsynTask(String strUrl, final CallBackString backString) {
        new AsyncTask<String, Integer, String>() {
            @Override
            protected String doInBackground(String... strings) {
                return httpGet(strings[0]);
            }
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                //接口回调的方法
                backString.getData(s);
            }
        }.execute(strUrl);
    }
    //接口================================
    public interface  CallBackString{
        void   getData(String s);
    }
    public  static String httpGet(String strUrl) {
        //设置url
        try {
            URL url = new URL(strUrl);
            //获取HttpURLConnection
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //设置为get请求
            connection.setRequestMethod("GET");
            //设置连接主机超时时间
            connection.setConnectTimeout(5000);
            //设置从主机读取数据超时
            connection.setReadTimeout(5000);
            //得到数据
            InputStream stream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            //拼接数据
            StringBuilder builder = new StringBuilder();
            String str = "";
            while ((str = reader.readLine()) != null) {
                builder.append(str);
            }
            //关闭连接
            connection.disconnect();
            //返回数据
            return builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_43898679/article/details/85718401