AsyncTask+httpClient請求數據

  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();


}
發佈了53 篇原創文章 · 獲贊 8 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章