HttpURLConnection ListView展示

public class Fragment01 extends Fragment{
    private static final String TAG = "MainActivity";
    private String url="http://api.iclient.ifeng.com/ClientNews?id=JS83,FOCUSJS83&action=defalult";
    private ListView listView;
    private MyHandler myHandler=new MyHandler();
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment01,container,false);
        listView = view.findViewById(R.id.listview);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        new Thread(){
            @Override
            public void run() {
                try {
                    URL u = new URL(url);
                    HttpURLConnection connection = (HttpURLConnection) u.openConnection();
                    connection.setConnectTimeout(5000);
                    if (connection.getResponseCode()==200){
                        InputStream stream = connection.getInputStream();
                        String json = Method(stream);
                        Message message = new Message();
                        message.what=0;
                        message.obj=json;
                        myHandler.sendMessage(message);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }.start();
    }
    public String Method(InputStream inputStream) throws IOException {
        int len=0;
        byte[] buffer=new byte[1024];
        StringBuffer stringBuffer = new StringBuffer();
        while ((len=inputStream.read(buffer))!=-1){
            String s = new String(buffer, 0, len);
            stringBuffer.append(s);
        }
        return stringBuffer.toString();
    }
    class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
         switch (msg.what){
             case 0:
                 String obj = (String) msg.obj;
                 Gson gson = new Gson();
                 Type type = new TypeToken<LinkedList<NewsBean>>() {
                 }.getType();
                 LinkedList<NewsBean> list = gson.fromJson(obj, type);
                 List<NewsBean.ItemBean> item = list.get(0).getItem();
                 MyBase myBase = new MyBase(getActivity(), item);
                 listView.setAdapter(myBase);
                 break;
         }
        }
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值