OKHttp网络请求封装

导入依赖

compile 'com.zhy:okhttputils:2.0.0'

 
---------------------------------------------------------------------------------------------------------------------------------------------------------------
写BaseBean类,用来作为请求数据进行解析的Bean类的父类,用来解析网络数据的Bean类继承此类

public class Basebean {
    private String code;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}
---------------------------------------------------------------------------------------------------------------------------------------------------------------
,用来解析网络数据的Bean类继承此类

public class MyBean extends Basebean{

    /**
     * code : 200
     * datas : {"class_list":[{"gc_id":"1","gc_name":"服饰鞋帽","type_id":"0","type_name":"","gc_parent_id":"0","commis_rate":"0","gc_sort":"255","gc_virtual":"0","gc_title":"","gc_keywords":"","gc_description":"","show_type":"1","image":"http://169.254.4.76/data/upload/mobile/category/05015381809285330.png","text":"女装/男装/内衣/运动/女鞋/男鞋/配饰/童装"},{"gc_id":"2","gc_name":"礼品箱包","type_id":"0","type_name":"","gc_parent_id":"0","commis_rate":"0","gc_sort":"255","gc_virtual":"0","gc_title":"","gc_keywords":"","gc_description":"","show_type":"1","image":"http://169.254.4.76/data/upload/mobile/category/05015381349504237.png","text":"潮流女包/时尚男包/功能箱包/礼品/奢侈品"},{"gc_id":"3","gc_name":"家居家装","type_id":"0","type_name":"","gc_parent_id":"0","commis_rate":"0","gc_sort":"255","gc_virtual":"0","gc_title":"","gc_keywords":"","gc_description":"","show_type":"1","image":"http://169.254.4.76/data/upload/mobile/category/05015381681266734.png","text":"家纺/灯具/生活日用/家装软饰/清洁日用/宠物生活"},{"gc_id":"256","gc_name":"数码办公","type_id":"0","type_name":"","gc_parent_id":"0","commis_rate":"0","gc_sort":"255","gc_virtual":"0","gc_title":"","gc_keywords":"","gc_description":"","show_type":"1","image":"http://169.254.4.76/data/upload/mobile/category/05015381190111257.png","text":"手机配件/摄影摄像/数码配件/时尚影音/电脑整机/电脑配件/外设产品/网络产品/办公打印/办公文仪/手机通讯"},{"gc_id":"308","gc_name":"家用电器","type_id":"0","type_name":"","gc_parent_id":"0","commis_rate":"0","gc_sort":"255","gc_virtual":"0","gc_title":"","gc_keywords":"","gc_description":"","show_type":"1","image":"http://169.254.4.76/data/upload/mobile/category/05015382063902705.png","text":"大家电/生活电器/厨房电器/个护健康/五金家装"},{"gc_id":"470","gc_name":"个护化妆","type_id":"0","type_name":"","gc_parent_id":"0","commis_rate":"0","gc_sort":"255","gc_virtual":"0","gc_title":"","gc_keywords":"","gc_description":"","show_type":"1","image":"http://169.254.4.76/data/upload/mobile/category/05015382211209809.png","text":"面部护理/身体护理/口腔护理/女性护理/男士护理/魅力彩妆/香水SPA"},{"gc_id":"530","gc_name":"珠宝手表","type_id":"0","type_name":"","gc_parent_id":"0","commis_rate":"0","gc_sort":"255","gc_virtual":"0","gc_title":"","gc_keywords":"","gc_description":"","show_type":"1","image":"http://169.254.4.76/data/upload/mobile/category/05015382869763762.png","text":"时尚饰品/纯金K金饰品/金银投资/银饰/钻石饰品/翡翠玉石/水晶玛瑙/宝石珍珠/婚庆/钟表手表"},{"gc_id":"593","gc_name":"食品饮料","type_id":"0","type_name":"","gc_parent_id":"0","commis_rate":"0","gc_sort":"255","gc_virtual":"0","gc_title":"","gc_keywords":"","gc_description":"","show_type":"1","image":"http://169.254.4.76/data/upload/mobile/category/05015382413708016.png","text":"进口食品/地方特产/休闲食品/粮油调味/中外名酒/饮料冲调/营养健康/亚健康调理/健康礼品/生鲜食品"},{"gc_id":"662","gc_name":"运动健康","type_id":"0","type_name":"","gc_parent_id":"0","commis_rate":"0","gc_sort":"255","gc_virtual":"0","gc_title":"","gc_keywords":"","gc_description":"","show_type":"1","image":"","text":"户外鞋服/户外装备/运动器械/纤体瑜伽/体育娱乐/成人用品/保健器械/急救卫生"},{"gc_id":"730","gc_name":"汽车用品","type_id":"0","type_name":"","gc_parent_id":"0","commis_rate":"0","gc_sort":"255","gc_virtual":"0","gc_title":"","gc_keywords":"","gc_description":"","show_type":"1","image":"http://169.254.4.76/data/upload/mobile/category/05015382972892418.png","text":"电子电器/系统养护/改装配件/汽车美容/座垫脚垫/内饰精品/安全自驾/整车"},{"gc_id":"825","gc_name":"玩具乐器","type_id":"0","type_name":"","gc_parent_id":"0","commis_rate":"0","gc_sort":"255","gc_virtual":"0","gc_title":"","gc_keywords":"","gc_description":"","show_type":"1","image":"http://169.254.4.76/data/upload/mobile/category/05015383078446336.png","text":"适用年龄/遥控/电动/毛绒布艺/娃娃玩具/模型玩具/健身玩具/动漫玩具/益智玩具/积木拼插/DIY玩具/创意减压/乐器相关"},{"gc_id":"888","gc_name":"厨具","type_id":"0","type_name":"","gc_parent_id":"0","commis_rate":"0","gc_sort":"255","gc_virtual":"0","gc_title":"","gc_keywords":"","gc_description":"","show_type":"1","image":"http://169.254.4.76/data/upload/mobile/category/05015382679643040.png","text":"烹饪锅具/刀剪菜板/收纳保鲜/水具酒具/餐具/茶具/咖啡具"},{"gc_id":"959","gc_name":"母婴用品","type_id":"0","type_name":"","gc_parent_id":"0","commis_rate":"0","gc_sort":"255","gc_virtual":"0","gc_title":"","gc_keywords":"","gc_description":"","show_type":"1","image":"http://169.254.4.76/data/upload/mobile/category/05015383177958780.png","text":"奶粉/营养辅食/尿裤湿巾/喂养用品/洗护用品/童车童床/服饰寝居/妈妈专区"},{"gc_id":"1037","gc_name":"虚拟充值","type_id":"0","type_name":"","gc_parent_id":"0","commis_rate":"0","gc_sort":"255","gc_virtual":"1","gc_title":"","gc_keywords":"","gc_description":"","show_type":"1","image":"http://169.254.4.76/data/upload/mobile/category/05015383410379550.png","text":"充值/游戏/票务"}]}
     */

    private int codeX;
    private DatasBean datas;
这里会有一个用注释写的父类中的code,删掉就好,不然会报错

---------------------------------------------------------------------------------------------------------------------------------------------------------------

写一个接口,用来执行接口回调

public interface MyInterface {
    public void onSuccess(Basebean basebean);
}

---------------------------------------------------------------------------------------------------------------------------------------------------------------

封装类,使用的是接口回调方法

public class Myhttp {
    private volatile static Myhttp myhttp;
    private Gson gson;

    private Myhttp() {
        gson = new Gson();
    }

    public static Myhttp gethttpUtil() {
        if (myhttp == null) {
            synchronized (Myhttp.class) {
                if (myhttp == null) {
                    myhttp = new Myhttp();
                }
            }
        }
        return myhttp;
    }

    //post请求
    public void post(final Context context, String url, Map<String, String> params,
                     final Class clazz, final MyInterface onNetListener) {
        if (TextUtils.isEmpty(url)) {
            throw new RuntimeException("url is null!!");
        }
        PostFormBuilder postFormBuilder = OkHttpUtils.post().url(url);
        //拼接参数
        for (Map.Entry<String, String> entry : params.entrySet()) {
            postFormBuilder.addParams(entry.getKey(), entry.getValue());
        }
        postFormBuilder.build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                showErrorInfo(context);
            }

            @Override
            public void onResponse(String response) {
                dealWithResponse(context, response, clazz, onNetListener);
            }
        });
    }

    /**
     * get 请求
     *
     * @param url
     * @param clazz
     * @param myinterface
     */
    public void get(final Context context, String url, final Class clazz, final MyInterface myinterface) {
        if (TextUtils.isEmpty(url)) {
            throw new RuntimeException("url is null!!!");
        }
        OkHttpUtils.get()
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        showErrorInfo(context);
                    }

                    @Override
                    public void onResponse(String response) {
                        dealWithResponse(context, response, clazz, myinterface);
                    }
                });
    }

    /**
     * 处理返回的数据
     *
     * @param response
     * @param clazz
     * @param myInterface
     */
    private void dealWithResponse(Context context, String response, Class clazz, MyInterface myInterface) {
        if (!TextUtils.isEmpty(response)) {
            Basebean bean = (Basebean) gson.fromJson(response, clazz);
            if (bean.getCode().equals("400")) {
                //提示错误信息
                showErrorInfo(context);
            } else {
                //返回正确结果
                if (myInterface != null) {

                    myInterface.onSuccess(bean);
                }
            }
        }
    }


    private void showErrorInfo(Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage("请求数据有误,请稍后再试!");
        builder.setPositiveButton("确定", null);
        builder.setNegativeButton("取消", null);
        builder.show();
    }

}

---------------------------------------------------------------------------------------------------------------------------------------------------------------

定义一个app全局类,记得注册

public class MyApp extends Application {
    private Myhttp myhttp;

    @Override
    public void onCreate() {
        super.onCreate();
        ZXingLibrary.initDisplayOpinion(this);
        myhttp = Myhttp.gethttpUtil();


    }

    public Myhttp getMyhttp() {
        return myhttp;
    }
}
---------------------------------------------------------------------------------------------------------------------------------------------------------------

然后就是调用了

 
 获得对象
App myApp = (App) getActivity().getApplication();
Myhttp myhttp = myApp.getMyhttp();

//封装的okhttp数据请求,也可以按照自己的用其他的方式,传入的参数是:上下文,网络接口,用来解析json串的bean类
,实例化接口
myhttp.get(getActivity(),url, Expand1.class, new MyInterface() {
    @Override
    public void onSuccess(final Basebean basebean) {
//通过接口回调得到解析完毕的Bean父类,使用的强转成解析类就可以了,剩下的就是正常使用
        Expand1 bean = (Expand1) basebean;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值