private ListView lv;
private String murl = "http://result.eolinker.com/k2BaduF2a6caa275f395919a66ab1dfe4b584cc60685573?uri=tt";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找控件
lv = findViewById(R.id.lv);
new MyAsyc().execute();
// MyAsyc myAsyc = new MyAsyc();
// myAsyc.execute();
}
//创建一个继承AsyncTask的类
class MyAsyc extends AsyncTask<Integer, Integer, String> {
private String data;
//执行后台任务前对UI做一些标记
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.i("TAG", "onPreExecute: ");
lv = findViewById(R.id.lv);
}
//耗时操作 相当于一个线程 Thread 在该方法中获取JSon
@Override
protected String doInBackground(Integer... integers) {
try {
URL url = new URL(murl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int responseCode = connection.getResponseCode();
data = "";
if (responseCode == HttpURLConnection.HTTP_OK) {
//获取输入流
InputStream inputStream = connection.getInputStream();
//读取输入流
byte[] b = new byte[1024 * 524];
//定义一个自带缓存的数组输入流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int length = 0;
while ((length = inputStream.read(b)) > -1) { //每次读的len>-1 说明是是有数据的
baos.write(b, 0, length);
}
//赋值给一个字符串
data = baos.toString();
Log.e("TAG","Data: " + data);
//关流 断开连接
inputStream.close();
connection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
//需要返回字符串 然后再onPostExecute方法中获取该值使用
return data;
}
//当后台操作结束时,此方法将会被调用,计算结果将做为参数传递到此方法中,直接将结果显示到UI组件上 相当于Handler
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null){
//开始解析 利用Gson
Gson Gson = new Gson();
FocusBean focusBean = Gson.fromJson(s, FocusBean.class);
List<FocusBean.ResultBean.DataBean> list = focusBean.getResult().getData();
if (list != null) {
MyAdapter myAdapter = new MyAdapter(MainActivity.this,list);
lv.setAdapter(myAdapter);
}
}else{
Toast.makeText(MainActivity.this,"数据为空",Toast.LENGTH_LONG);
return;
}
}
//更新进度
@Override
protected void onProgressUpdate(Integer... values) {
Log.i("TAG", "onProgressUpdate: ");
Toast.makeText(MainActivity.this, "加载中。。。" + values.toString(), Toast.LENGTH_LONG).show();
super.onProgressUpdate(values);
}
}
AsyncTask的GET方法请求网络Json
最新推荐文章于 2021-07-28 14:47:59 发布