第四步
MyAsyncTask
package com.bawei.test.xlistview; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import com.google.gson.Gson; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; public class MyAsyncTask extends AsyncTask<String,Integer,String> { static DataBean mDatabean; Context con; String url; String type; ListView listView; public MyAsyncTask(Context con, String url, String type, ListView listView) { super(); this.url=url; this.con=con; this.type=type; this.listView=listView; } //网络请求 public void GetDatas(String murl, String mtype) { //头条服务器地址 try { URL url = new URL(murl); //打开连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //设置 connection.setRequestMethod(mtype); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); //post方式要提交参数给服务器...以流的方式提交给服务器 connection.setDoOutput(true); //设置请求参数的类型 //connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String params = "key=8d6e3228d25298f13af4fc40ce6c9679&num=10"; //参数以流的形式写给服务器...字节数组的形式写出去 connection.getOutputStream().write(params.getBytes()); //响应 int responseCode = connection.getResponseCode(); if (responseCode == 200) { //获取输入字节流 InputStream inputStream = connection.getInputStream(); String json = streamToString(inputStream, "utf-8"); Log.i("json", json); //解析...解析完成之后发送到主线程,设置适配器 Gson gson = new Gson(); mDatabean = gson.fromJson(json, DataBean.class); Log.i("json", mDatabean.getCode()); } } catch (Exception e) { e.printStackTrace(); } } private String streamToString(InputStream inputStream, String charset) { try { InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String s = null; StringBuilder builder = new StringBuilder(); while ((s = bufferedReader.readLine()) != null) { builder.append(s); } bufferedReader.close(); return builder.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); List<DataBean.NewslistBean> listbean=mDatabean.getNewslist(); //设置适配器 MyAdapter myAdapter = new MyAdapter(listbean,con); listView.setAdapter(myAdapter); } public MyAsyncTask() { super(); } @Override protected String doInBackground(String... strings) { GetDatas(url, type); return null; } }