NetDataUtil_获取网络数据的工具类

来源:互联网 发布:房屋外观设计简单软件 编辑:程序博客网 时间:2024/05/17 02:08
public class NetDataUtil {


    /**
     * 获取网络数据的方法
     * @param path
     */
    public static void getData(final String path, Context context, final JsonCallBack callBack){
        //1.获取网络数据之前要判断网络的状态
        if (NetWorkUtil.isConn(context)){
            //可用就去获取数据...在这可以吐司
            AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {
                @Override
                protected String doInBackground(Void... voids) {
                    try {
                        URL url = new URL(path);


                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();


                        connection.setRequestMethod("GET");
                        connection.setReadTimeout(5000);
                        connection.setConnectTimeout(5000);


                        int responseCode = connection.getResponseCode();
                        if (responseCode == 200){
                            InputStream inputStream = connection.getInputStream();


                            String json = StringUtil.streamToString(inputStream,"utf-8");


                            return json;


                        }


                    } catch (Exception e) {
                        e.printStackTrace();
                    }




                    return null;
                }


                @Override
                protected void onPostExecute(String s) {
                    //以前我们做的操作是直接解析....现在在工具类里面通过接口回调的形式,把json格式的数据传递给具体调用这个方法的那个类


                    callBack.getJson(s);


                }
            };


            //执行
            asyncTask.execute();


        }else {
            NetWorkUtil.showNoNetWorkDlg(context);
        }


    }


}