简单的异步获取网络数据

AsyncTask asyncTask = new AsyncTask() {
            @Override
            protected String doInBackground(Void... voids) {

                String path = "网络数据接口";
                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 = streamToString(inputStream,"utf-8");

                        return json;
                    }

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

                return "";
            }

            @Override
            protected void onPostExecute(String json) {
                Gson gson = new Gson();
                DataDataBean dataDataBean = gson.fromJson(json, DataDataBean.class);


                //添加
                list.addAll(dataDataBean.getData());

             
              
            }
        };

      asyncTask .execute();

    }

  

你可能感兴趣的:(简单的异步获取网络数据)