网络请求数据

来源:互联网 发布:hadoop wordcount源码 编辑:程序博客网 时间:2024/06/06 19:40
//首先要写AsyncTask方法,写耗时的网络操作new AsyncTask<String,Integer,String>(){    @Override    protected String doInBackground(String... params) {        //获得地址        String url=params[0];        URL urll=null;        String ss="";        HttpURLConnection httpURLConnection=null;        try {            urll=new URL(url);            httpURLConnection= (HttpURLConnection) urll.openConnection();            //设置获取时间            httpURLConnection.setConnectTimeout(5000);            httpURLConnection.setReadTimeout(5000);            //获取网络请求            int responseCode = httpURLConnection.getResponseCode();            if(responseCode==200){            InputStream inputStream = httpURLConnection.getInputStream();            byte[] b=new byte[1024];            int len=0;            //循环读取字符串            while ((len=inputStream.read(b))!=-1){                ss+=new String(b,0,len);            }            //记住关流                inputStream.close();            }            } catch (Exception e) {                e.printStackTrace();            }            //返回字符串            return ss;    }    @Override    protected void onPostExecute(String s) {    super.onPostExecute(s);    //开始解析字符串    Bean bean = new Gson().fromJson(s, Bean.class);    newslist = bean.getNewslist();    //添加到listview适配器里    adapter = new Adapter(MainActivity.this, newslist);    ListView.setAdapter(adapter);}}.execute("https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10");
原创粉丝点击