Retrofit工具类(Retrofit二次封装)

来源:互联网 发布:2017淘宝数据魔方 编辑:程序博客网 时间:2024/06/05 16:17

本文是原创,转载请注明,谢谢。

之前一直用的XUtils,方便快捷,但是由于与后台对接的方式有了新的规范和模式变更,XUtils满足不了我们新的需求,所以开始使用Retrofit,由于Retrofit本身属于重量级的网络框架,不封装的话在项目中会非常的繁琐,所以有了下面这个工具类。
依赖scalars用于获取字符串,依赖Gson可以获取到Model对象,
因为我们的解析有另外的工具类,而且后台刚刚换框架,为了避免多次更改,所以依赖的是scalars,先获取字符串,这样方便调试。

    compile 'com.squareup.retrofit2:retrofit:2.2.0'    compile 'com.squareup.retrofit2:converter-scalars:2.2.0'

先来看看Retrofit封装之后的用法

网络请求时添加的参数我放在Map里面,不确定是否需要传文件,所以Map的value用了Object占位,每次new的时候很不自在,直接继承了一个

public class RequestParam extends HashMap<String,Object>{}
        RequestParam param=new RequestParam();        param.put("name", "韦兆都");//普通字符串参数        param.put("image", new File(""));//上传文件        //第一个参数:URL        //第二个参数:网络请求需要传的参数,是个Map        //第三个参数:回调        HttpUtils.postRequest("www.1024.com", param, new RetrofitCallBack() {            @Override            public void onSuccess(Response<String> response, Call<String> call) {            }            @Override            public void onFailure(Call<String> call, Throwable t) {            }            @Override            public void onException(Exception e) {            }        });

需要可操控的去取消网络请求时,把对象提取出来,在需要取消的时候调用cancel即可。

        RequestParam param=new RequestParam();        param.put("name", "韦兆都");//普通键值对        param.put("image", new File(""));//上传文件        Call<String> call = HttpUtils.postRequest("www.1024.com", param, new RetrofitCallBack() {            @Override            public void onSuccess(Response<String> response, Call<String> call) {            }            @Override            public void onFailure(Call<String> call, Throwable t) {            }            @Override            public void onException(Exception e) {            }        });        //比如DaiLog关闭监听的方法中放入        call.cancel();

************************上面是用法 下面贴代码*************

首先是RetrofitInterface

public interface RetrofitInterface {    /**     * POST请求     */    @POST    Call<String> postRequest(@Url String url, @Body RequestBody body);    /**     * GET请求     */    @GET    Call<String> getRequest(@Url String url);    /**     * PUT请求     */    @PUT    Call<String> putRequest(@Url String url, @Body RequestBody body);}

看了很多Retrofit的介绍,我还是比较喜欢RequestBody这参数,合我胃口,不论是传文件还是传普通的键值对,都可以放入这个请求体当中。至于我用@URL这个注解,也是因为比较万能,全额替换url。

接下来是自定义回调的接口,因为在网络请求的步骤是在工具类当中执行的异步,所以需要来一发接口回调。

public interface RetrofitCallBack  {    void onSuccess(Response<String> response, Call<String> call);    void onFailure(Call<String> call, Throwable t);    void onException(Exception e);}

工具类使用时调用下面四个方法,对应四种请求类型:

    /**     * get请求     * @param url     * @param callback     * @return     */    public static Call<String> getRequest(String url, RetrofitCallBack callback) {        Call<String> connect = null;        try {            connect = connect(url, callback);        } catch (Exception e) {            e.printStackTrace();        }        return connect;    }    /**     * post请求     * @param url     * @param map     * @param callback     * @return     */    public static Call<String> postRequest(String url, Map<String, Object> map, RetrofitCallBack callback) {        Call<String> connect = null;        try {            connect = connect(POST_REQUEST, url, map, callback);        } catch (Exception e) {            e.printStackTrace();        }        return connect;    }    /**     * delete请求     * @param url     * @param map     * @param callback     * @return     */    public static Call<String> deleteRequest(String url, Map<String, Object> map, RetrofitCallBack callback) {        Call<String> connect = null;        try {            connect = connect(DELETE_REQUEST, url, map, callback);        } catch (Exception e) {            e.printStackTrace();        }        return connect;    }    /**     * put请求     * @param url     * @param map     * @param callback     * @return     */    public static Call<String> putRequest(String url, Map<String, Object> map, RetrofitCallBack callback) {        Call<String> connect = null;        try {            connect = connect(PUT_REQUEST, url, map, callback);        } catch (Exception e) {            e.printStackTrace();        }        return connect;    }

下面方法对应网络请求中是否给请求体添加参数

get无参请求

    /**     * 无参连接     * @param url     * @param callback     */    private static Call<String> connect(final String url, final RetrofitCallBack callback) {        Call<String> call = getInstance().getRequest(url);        call.enqueue(new Callback<String>() {            @Override            public void onResponse(Call<String> call, Response<String> response) {                callback.onSuccess(response, call);            }            @Override            public void onFailure(Call<String> call, Throwable t) {                callback.onFailure(call, t);            }        });        return call;    }

post、put、delete带参请求:

/**     * 有参连接     * @param type     * @param url     * @param map     * @param callback     */    private static Call<String> connect(int type, String url, Map<String, Object> map, final RetrofitCallBack callback) {//        FormBody.Builder builder = new FormBody.Builder();//        for (Map.Entry<String, Object> entry : map.entrySet()) {//            String key = entry.getKey();//            Object value = entry.getValue();//            builder.add(key, value.toString());//            Log.d("params--", "key:" + key + "     value:" + value);//        }        //补充一下,上面是默认的表单提交,下面是form-data,分别放到两个方法中,一个用于带文件参数的,一个用于不带文件的,当然也可以和后台协商,统一用一种规则。        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);        for (Map.Entry<String, Object> entry : map.entrySet()) {            String key = entry.getKey();            Object value = entry.getValue();            if (value.getClass().getName().equals("java.io.File")) {                File file = (File) value;                builder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file));                Log.d("params--","key:"+ key + "---value:"+file.getPath());            } else {                builder.addFormDataPart(key, value.toString());                Log.d("params--","key:"+ key + "---value:"+value);            }        }        RequestBody requestBody = null;        try {            requestBody = builder                    .build();        } catch (Exception e) {            e.printStackTrace();            callback.onException(e);        }        Call<String> call = null;        switch (type) {            case POST_REQUEST:                call = getInstance().postRequest(url, requestBody);                break;            case PUT_REQUEST:                call = getInstance().putRequest(url, requestBody);                break;            case DELETE_REQUEST:                call = getInstance().deleteRequest(url, requestBody);                break;        }        call.enqueue(new Callback<String>() {            @Override            public void onResponse(Call<String> call, Response<String> response) {                callback.onSuccess(response, call);            }            @Override            public void onFailure(Call<String> call, Throwable t) {                callback.onFailure(call, t);            }        });        return call;    }

有些东西以后再扩展了,暂时就这些。

2017、6、5编辑:
这两天用delete请求遇到BUG,说什么参数啥啥啥的,无参没问题,有参会报错,先记着,以后再处理。

1 0