网络数据接口Gson解析

private class MyAsync extends AsyncTask<String, Integer, String> {
    @Override
    protected String doInBackground(String... strings) {

        try {
            //路径
            String path = "http://www.xieast.com/api/news/news.php?page=1";
            //获取地址
            URL url = null;
            url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            //设置延迟时间
            httpURLConnection.setConnectTimeout(5000);
            httpURLConnection.setReadTimeout(5000);
            httpURLConnection.setRequestMethod("GET");
            //判断是否为空
            if (httpURLConnection.getResponseCode()==200){
                //创建输入流
                InputStream inputStream = httpURLConnection.getInputStream();
                //创建输出流
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                //创建数组
                byte[] bytes = new byte[1024];
                //创建长度
                int len = 0;
                //遍历输出
                while ((len = inputStream.read(bytes))!=-1){
                    outputStream.write(bytes,0,len);
                }
                //关流
                outputStream.close();
                inputStream.close();
                //将字符串转换成Gson文件
                String json = outputStream.toString();
                //返回数据
                return  json;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    //更新UI
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        //创建gson
        Gson gson = new Gson();
        //解析gson
        User user = gson.fromJson(s, User.class);
        List<User.DataBean> data = user.getData();
        //创建适配器
        MyAdapter myAdapter = new MyAdapter(data,MainActivity.this);
        //设置适配器
        list_view.setAdapter(myAdapter);
    }
}

猜你喜欢

转载自blog.csdn.net/h_builder/article/details/80964679