获取网络json解析中的图片

//Android Studio

json解析的bean类为: Student

使用Gson解析:Alt+insert     选中GsonFormat  json数据复制-->黏贴进入  快速解析json

新建class类

public class NetWorkUtil {
    private int responseCode;
    /**
     * 获取图片并返回;
     * @param urlString
     * @return
     */
    public Bitmap getNetImage(String urlString){
        try {
            //得到URL对象,这个对象可以打开连接
            URL url = new URL(urlString);
            //打开连接,HttpURLConnection:是URLConnection的子类;子类的方法比较多;都用子类
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            //服务器返回的状态码
            int responseCode = urlConnection.getResponseCode();
            //请求成功
            if (responseCode == 200){
                InputStream inputStream = urlConnection.getInputStream();
                //BitmapFactory类封装了好多关于图片处理的方法;
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                return  bitmap;
            }else {
                Log.e("wzq请求图片","responseCode:"+ responseCode);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 请求json字符串,
     * @param urlString url
     * @return   json字符串
     */
    public String getNetString(String urlString){
        try {
            //得到URL对象,这个对象可以打开连接
            URL url = new URL(urlString);
            //打开连接,HttpURLConnection:是URLConnection的子类;子类的方法比较多;都用子类
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            //服务器返回的状态码
            int responseCode = urlConnection.getResponseCode();
            //请求成功
            if (responseCode == 200){
                InputStream inputStream = urlConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder();
                String stringTemp = "";
                while ((stringTemp = bufferedReader.readLine()) != null) {
                    stringBuilder.append(stringTemp);
                }
                String result = stringBuilder.toString();
                Log.e("wzq请求json", "result:" + result);
                return result;
            }else {
                Log.e("wzq","responseCode:"+ responseCode);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}




///..................主    .....MainActivity

public class MainActivity extends AppCompatActivity {
    private ListView lv;
   List<Student.DataBean> lists = new ArrayList<>();
    private MAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv = (ListView) findViewById(R.id.lv);
        initData();
        mAdapter = new MAdapter();
        lv.setAdapter(mAdapter);
    }
    /**
     * 请求网络数据
     */
    private void initData() {
        //记得要在子线程中写
        new Thread() {
            @Override
            public void run() {
                super.run();
                String netString = new NetWorkUtil().getNetString("http://api.expoon.com/AppNews/getNewsList/type/1/p/1");
                Gson gson = new Gson();
                Student student = gson.fromJson(netString, Student.class);
                lists = student.getData();
                mAdapter.notifyDataSetChanged();
            }
        }.start();
    }

    class MAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return lists.size();
        }
        @Override
        public Object getItem(int i) {
            return lists.get(i);
        }
        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View containerView, ViewGroup viewGroup) {
            View view = View.inflate(MainActivity.this, R.layout.list_item, null);
            ImageView iv = (ImageView) view.findViewById(R.id.iv);
            //把图片url传递给asyncTask
            new MAsyncTask(iv).execute(lists.get(i).getPic_url());
            return view;
        }
    }

    /**
     * alt+insert 自动选择要实现的方法等等
     * 第一个参数表示要执行的任务通常是网络的路径
     * 第二个参数表示进度Integer
     * 第三个参数表示任务执行的返回结果
     */
    class MAsyncTask extends AsyncTask<String, Void, Bitmap> {
        ImageView iv;
        public MAsyncTask(ImageView imageView){
            this.iv = imageView;
        }

        //这个是请求网络之前的调用的方法,也是最先调用的方法,可以初始化一些ui等;这个方法是在主线程里运行的
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        /**
         * String... strings--->这个是可变参数;
         * 这个方法是在后台执行的,不能更新ui,是子线程
         * 这个方法的返回值会返回给
         */
        @Override
        protected Bitmap doInBackground(String... strings) {
            Bitmap bitmap = null;
            try {
                //取的可变参数的第一个元素;是url;
                URL url = new URL(strings[0]);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                //设置链接超时时间;
                urlConnection.setConnectTimeout(6000);
                //设置读取返回数据的超时时间
                urlConnection.setReadTimeout(5000);
                int responseCode = urlConnection.getResponseCode();
                //响应码200代表链接和返回数据成功
                if (responseCode == 200) {
                    InputStream inputStream = urlConnection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(inputStream);
                } else {
                    Log.e("wzq", "doInBackground: responseCode" + responseCode);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bitmap;
        }
        /**
         * 这个方法是运行在主线程的
         * 当doInBackground执行完, 会自动回调这个方法,来更新ui;
         *
         * @param bitmap
         */
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            iv.setImageBitmap(bitmap);
        }
        //主线程可以更新ui;
        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }
    }
}





阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页