AsyncTask+httpClient请求数据

来源:互联网 发布:流程审批软件 编辑:程序博客网 时间:2024/06/04 19:59
  AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {        //运行在后台...类似子线程,,,做耗时的操作(访问网络的操作)        @Override        protected String doInBackground(Void... voids) {            try {                /**                 * httpClient已经过时了,在使用的时候需要在build,grandle下面加一行代码,去支持httpClient                 */                SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());                String path2="https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10&page=1";                //1.创建一个客户端对象                HttpClient client = new DefaultHttpClient();                //2.创建一个请求的对象...请求的对象可以是get也可以是post                HttpGet httpGet = new HttpGet(path2);                //3.客户端对象执行get请求....返回值是一个响应的对象                HttpResponse httpResponse = client.execute(httpGet);                //获取状态码                int statusCode = httpResponse.getStatusLine().getStatusCode();                if (statusCode == 200) {                    //获取响应的实体内容...字节流...先获取实体内容的对象...在获取内容                    InputStream inputStream = httpResponse.getEntity().getContent();                    String json = streamToString(inputStream, "utf-8");                    //返回                    return json;                }            } catch (Exception e) {                e.printStackTrace();            }            return null;        }        //接收到doInBackground发送回来的数据....处于主线程,,,更新界面的操作写在这里        @Override        protected void onPostExecute(String s) {//s就是doInBackground返回的json数据            //在这里接收到doInBackground返回的json数据,,,解析设置适配器            Gson gson = new Gson();            DataDataBean dataDataBean = gson.fromJson(s, DataDataBean.class);            List<DataDataBean.NewslistBean> list = dataDataBean.getNewslist();            //设置适配器            MyAdapter myAdapter = new MyAdapter(list, MainActivity.this);            lv.setAdapter(myAdapter);        }    };    /**     * 异步任务要执行,,,需要手动的去调用excute方法     */    asyncTask.execute();}