安卓网络请求数据,使用异步任务

来源:互联网 发布:铁道工程就业 知乎 编辑:程序博客网 时间:2024/05/29 04:04

写工具类方便多次调用

public class JavaUtils {    public String getString(String surl){        String str="";        try {            URL url = new URL(surl);            HttpURLConnection http=(HttpURLConnection) url.openConnection();            int code = http.getResponseCode();            if(code==200){                InputStream in = http.getInputStream();                byte[] b=new byte[1024];                int len=0;                while((len=in.read(b))!=-1){                    str+=new String(b,0,len);                }            }        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return str;    }}

异步任务的使用(AsyncTask)

new AsyncTask<String,Integer,String>(){                    @Override                    protected String doInBackground(String... strings) {                        String string = new JavaUtils().getString("http://gank.io/api/data/"+st+"/10/"+"1");                        return string;                    }                    @Override                    protected void onPostExecute(String s) {                        super.onPostExecute(s);                 new Gson().fromJson(s, JavaBean.class);                                            }                }.execute();



原创粉丝点击