HttpUtils 类的 接口回调方式的简单实现

本文介绍了一个封装好的HTTP网络请求工具类,通过单例模式提供全局唯一实例,并使用异步任务进行网络数据加载,支持成功与错误回调。文章展示了如何在实际项目中应用此工具类进行数据获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//这是封装的HttpUtils类

public class HttpUtils {
    /**
     *  静态内部类单例模式
     */
    private HttpUtils(){}

    private static class SingleTon {
        private static HttpUtils httpUtils = new HttpUtils();
    }
    public static HttpUtils getInstance() {
        return SingleTon.httpUtils;
    }

    // 请求网络数据方法
    public void getData(String url,CallBack callBack) {
        new LoadDataTask(callBack).execute(url);
    }

    //这个接口当做 LoadDataTask异步任务类的成员变量传进去,调用接口中方法回调
    public CallBack callBack;
    //声明一个接口回调数据
    public interface CallBack{
        void onSuccess(String json);
        void onError(String error);
    }
    //网络请求异步任务类
    class LoadDataTask extends AsyncTask <String, Void, String> {
        CallBack callBack;//通过构造方法传进来的接口对象
        public LoadDataTask(CallBack callBack) {//构造方法
            this.callBack = callBack;
        }
        @Override
        protected String doInBackground(String... strings) {//子线程执行网络请求
            return getData(strings[0]);
        }
        @Override
        protected void onPostExecute(String s) {//UI线程中回调数据
            super.onPostExecute(s);
            if (s == null) {
                callBack.onError("数据为空,请检查网络");
            }else
                callBack.onSuccess(s);
        }
    }
    //在子线程执行网络请求的具体操作
    private String getData(String url) {
        try {
            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return Stream2String(conn.getInputStream());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    //流转换字符串
    private String Stream2String(InputStream inputStream) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer stringBuffer = new StringBuffer();
        String s = null;
        while ((s = br.readLine()) != null) {
            stringBuffer.append(s);
            //Log.i("aaa", s);
        }
        return stringBuffer.toString();
    }


}

//这是活动中调用HttpUtils类的完整实例

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_shop_list);
    listView = findViewById(R.id.shop_listView);

    //给listView添加进来一个头布局,
    View headView = View.inflate(this, R.layout.head_view, null);
    //获取ListView对象
    ListView refreshableView = listView.getRefreshableView();
    //设置headView的宽高
    AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT);
    headView.setLayoutParams(layoutParams);
    //查找头布局中的控件
    viewPager = headView.findViewById(R.id.headView_viewPager);
    pointContainer = headView.findViewById(R.id.point_container);
    //添加头布局
    refreshableView.addHeaderView(headView);
    //创建viewpager的图片地址集合
    bannerList = new ArrayList <>();
    //创建图片适配器

    listView.setMode(PullToRefreshBase.Mode.BOTH);
    //设置listView监听
    SetRefreshListener();

    shopAdapter = new ShopAdapter(this,goodsList);
    listView.setAdapter(shopAdapter);

    //这里调用网络请求工具类
    httpUtils = HttpUtils.getInstance();
    httpUtils.getData(Api.SHOP_PAGE+page,callBack);//这个callBack是此活动中对HttpUtils里接口的实现类

    //viewpager的图片资源
    httpUtils.getData(Api.BANNER_PAGE, new HttpUtils.CallBack() {
        @Override
        public void onSuccess(String json) {
            ShopBanner shopBanner = gson.fromJson(json, ShopBanner.class);
            List <ShopBanner.DataBean> data = shopBanner.getData();
            //创建imageVie集合
            imageViewList = new ArrayList <>();
            for (int i = 0; i < data.size(); i++) {
                //bannerList.add(data.get(i).getIcon());
                //创建小圆点
                createPoint(i);
            }
            shopViewPagerAdapter viewPagerAdapter = new shopViewPagerAdapter(ShopListActivity.this,data,imageViewList,handler);
            viewPager.setAdapter(viewPagerAdapter);
            handler.sendEmptyMessageDelayed(0, 1000);
        }
        //创建轮播图指示器
        private void createPoint(int i) {
            LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(15, 15);
            layoutParams1.setMargins(10,0,10,0);
            ImageView imageView = new ImageView(ShopListActivity.this);
            imageView.setLayoutParams(layoutParams1);
            if(i == 0){
                imageView.setImageResource(R.drawable.solid_round);
            }
            else{
                imageView.setImageResource(R.drawable.solid_line);
            }
            pointContainer.addView(imageView);
            imageViewList.add(imageView);
        }

        @Override
        public void onError(String error) {
        }
    });
}

//活动中创建一个类实现网络请求工具类的接口
class LoadData implements HttpUtils.CallBack{
    @Override
    public void onSuccess(String json) {
        Goods goods = gson.fromJson(json, Goods.class);
        if (page == 1) {
            goodsList.clear();
        }
        goodsList.addAll(goods.getData());
        shopAdapter.notifyDataSetChanged();
        listView.onRefreshComplete();
    }

    @Override
    public void onError(String error) {
        Toast.makeText(ShopListActivity.this,error,Toast.LENGTH_SHORT).show();
    }
}

//设置listView的上下拉刷新
private void SetRefreshListener() {
    listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2 <ListView>() {
        @Override
        public void onPullDownToRefresh(PullToRefreshBase <ListView> refreshView) {
            page=1;
            Toast.makeText(ShopListActivity.this, "已到光的尽头", Toast.LENGTH_SHORT).show();
            httpUtils.getData(Api.SHOP_PAGE+page,callBack);
        }
        @Override
        public void onPullUpToRefresh(PullToRefreshBase <ListView> refreshView) {
            page++;
            httpUtils.getData(Api.SHOP_PAGE+page,callBack);
        }
    });
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值