第一步: postman测试接口数据,查看是否返回成功 第二步:需要添加的依赖 implementation ‘com.google.guava:guava:16.0.1’ implementation ‘com.google.code.gson:gson:2.2.4’ Ctrl C/V 到项目的build.gradle,同步 第三步: File–Settings–Plugins搜索GsonFormat,点击下载 封装接口数据,alt+S 将接口数据粘贴,Format–OK,自动生成 布局就不在这里详细写了
private List<封装接口数据的类名> list; private XlistAdapter xlistAdapter;//这里我是用xlistview实现的布局 @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view=inflater.inflate(R.layout.movies,container,false); //初始化数据 initData(count); return view; } private void initData(final int count) { //创建子线程,主线程中不能做耗时操作,而子线程不能更新UI,我们可以用handler/AsyncTask发送消息 new Thread() { @Override public void run() { super.run(); try { URL url = new URL("网址"); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("GET"); httpURLConnection.setConnectTimeout(5000); httpURLConnection.setReadTimeout(5000); httpURLConnection.connect(); int responseCode = httpURLConnection.getResponseCode(); if (responseCode == 200) { InputStream inputStream = httpURLConnection.getInputStream(); Message message = Message.obtain(); message.obj = CharStreams.toString(new InputStreamReader(inputStream, "UTF-8")); message.what = 0; handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } }.start(); } Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 0: String json = (String) msg.obj; Gson gson = new Gson(); Lei lei = gson.fromJson(json, Lei.class); list = lei.getResult(); xlistAdapter = new XlistAdapter( MainActivity.this,list); xListView.setAdapter(xlistAdapter); xlistAdapter.notifyDataSetChanged();//刷新适配器 break; } } }; @Override public void onDestroy() { super.onDestroy(); handler.removeMessages(0); }