public class MyTask extends AsyncTask<String,Void,String> { private StringBuilder builder; //申请一个接口类对象 private Icallbacks icallbacks; //将无参构造设置成私有的,使之在外部不能够调用 private MyTask(){} //定义有参构造方法 public MyTask(Icallbacks icallbacks) { this.icallbacks = icallbacks; } @Override protected String doInBackground(String... strings) { try { URL url=new URL(strings[0]); HttpURLConnection urlConnection =(HttpURLConnection) url.openConnection(); //设置 urlConnection.setRequestMethod("GET"); urlConnection.setConnectTimeout(5000); urlConnection.setConnectTimeout(5000); //判断 if (urlConnection.getResponseCode()==200){ InputStream inputStream=urlConnection.getInputStream(); BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream)); String str; builder = new StringBuilder(); //循环 while((str=reader.readLine())!=null){ builder.append(str); } return builder.toString(); } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); //解析,封装到bean,更新ui组件 icallbacks.updateUiByjson(s); } //定义一个接口 public interface Icallbacks{ /** * 根据回传的json字符串,解析并更新页面组件 * @param jsonstr */ void updateUiByjson(String jsonstr); } }
MyTask网址解析
最新推荐文章于 2019-04-16 21:06:57 发布