public class Fragment01 extends Fragment{ private static final String TAG = "Activity---"; private ListView listView; private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case 0: String json = (String) msg.obj; Gson gson = new Gson(); //集合获取 Type listType = new TypeToken<LinkedList<NewBean>>(){}.getType(); LinkedList<NewBean>list=gson.fromJson(json, listType); List<NewBean.ItemBean> item = list.get(0).getItem(); MyAdapter myAdapter = new MyAdapter(getActivity(), item); listView.setAdapter(myAdapter); break; } } }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment01_layout, container, false); listView = view.findViewById(R.id.listview); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); new Thread(){ @Override public void run() { try { URL u=new URL(HttpConfig.ONE_URL); HttpURLConnection conn= (HttpURLConnection) u.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); int responseCode = conn.getResponseCode(); if (responseCode==200){ InputStream inputStream = conn.getInputStream(); String json = method(inputStream); Message message = Message.obtain(); message.what=0; message.obj=json; handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } }.start(); } public String method(InputStream inputStream) throws IOException { int len = 0; byte[] butter = new byte[1024]; StringBuffer stringBuffer = new StringBuffer(); while ((len = inputStream.read(butter)) != -1) { String s = new String(butter, 0, len); stringBuffer.append(s); } Log.d(TAG, "method: " + stringBuffer.toString()); return stringBuffer.toString(); } }
HttpURlConnection获取接口,handler
最新推荐文章于 2023-05-25 09:47:51 发布