基于Retrofit、OkHttp、Gson封装通用网络框架

背景

android开发过程中网络请求作为最重要的组成部分之一,然而对于大部分android开发者在网络请求上有太多疑惑,不知道如何去选型?通过原生的HttpClient、HttpUrlConnection封装?还是通过第三方框架再封装?笔者以为采用广泛被使用的第三方网络框架再封装为上策,因为这些网络框架如retrofit、okhttp、volley等是被全球android开发者维护着,无论在功能上、性能上、还是代码简洁性都相对于自己通过原生实现的给力.

目的

致力封装一个简洁、实用、易移植的网络框架模块.

正题

今天笔者就给大家基于retrofit + okhttp + gson 封装一个通用易懂的网络框架模块.
首先我们需要在gradle文件中将第三方依赖引入项目,代码如下:

dependencies {
    // retrofit + okhttp + gson
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
}

接着开始我们的封装之路......

首先我们需要写一个参数常量类,用于定义一些常量,如请求Url地址、接口返回信息,代码如下:

/**
 * @className: InterfaceParameters
 * @classDescription: 参数配置
 * @author: leibing
 * @createTime: 2016/8/30
 */

public class InterfaceParameters {
    // 请求URL
    public final static String REQUEST_HTTP_URL = BuildConfig.API_URL;
    // 接口返回结果名称
    public final static String INFO = "info";
    // 接口返回错误码
    public final static String ERROR_CODE = "errorcode";
    // 接口返回错误信息
    public final static String ERROR_MSG = "errormsg";
}

然后写一个网络请求封装类JkApiRequest.class,采用单例的方式,配置网络请求参数以及返回网络请求api实例,代码如下:

/**
 * @className:JkApiRequest
 * @classDescription:网络请求
 * @author: leibing
 * @createTime: 2016/8/30
 */
public class JkApiRequest {
    // sington
    private static JkApiRequest instance;
    // Retrofit object
    private Retrofit retrofit;

    /**
     * Constructor
     * @author leibing
     * @createTime 2016/08/30
     * @lastModify 2016/08/30
     * @param
     * @return
     */
    private JkApiRequest(){
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new OkHttpInterceptor())
                .build();
        retrofit = new Retrofit.Builder()
                .baseUrl(InterfaceParameters.REQUEST_HTTP_URL)
                .addConverterFactory(JkApiConvertFactory.create())
                .client(client)
                .build();
    }

    /**
     * sington
     * @author leibing
     * @createTime 2016/08/30
     * @lastModify 2016/08/30
     * @param
     * @return
     */
    public static JkApiRequest getInstance(){
        if (instance == null){
            instance = new JkApiRequest();
        }
        return instance;
    }

    /**
     * create api instance
     * @author leibing
     * @createTime 2016/08/30
     * @lastModify 2016/08/30
     * @param service api class
     * @return
     */
    public <T> T create(Class<T> service) {
        return retrofit.create(service);
    }
}

上面代码有两个网络请求参数需要注意, OkHttpInterceptor 、JkApiConvertFactory.
OkHttpInterceptor 作为网络请求拦截器,可以拦截请求的数据以及响应的数据,有助于我们排查问题,而JkApiConvertFactory 是作为Convert工厂,这里我所做的就是解析返回来的数据,将数据进行Gson处理就是在这里面.

OkHttpInterceptor代码如下:

/**
 * @className: OkHttpInterceptor
 * @classDescription: Http拦截器
 * @author: leibing
 * @createTime: 2016/08/30
 */
public class OkHttpInterceptor implements Interceptor {

    private static final Charset UTF8 = Charset.forName("UTF-8");

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();

        // 获得Connection,内部有route、socket、handshake、protocol方法
        Connection connection = chain.connection();
        // 如果Connection为null,返回HTTP_1_1,否则返回connection.protocol()
        Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
        // 比如: --> POST http://121.40.227.8:8088/api http/1.1
        String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;

        System.out.println("ddddddddddddddddddd requestStartMessage = " + requestStartMessage);

        // 打印 Response
        Response response;
        try {
            response = chain.proceed(request);
        } catch (Exception e) {
            throw e;
        }
        ResponseBody responseBody = response.body();
        long contentLength = responseBody.contentLength();

        if (bodyEncoded(response.headers())) {

        } else {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            Charset charset = UTF8;
            if (contentLength != 0) {
                // 获取Response的body的字符串 并打印
                System.out.println("ddddddddddddddddddddddddd response = " + buffer.clone().readString(charset));
            }
        }
        return response;
    }

    private boolean bodyEncoded(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
    }
}

JkApiConvertFactory代码如下:

/**
 * @className: JkApiConvertFactory
 * @classDescription: this converter decode the response.
 * @author: leibing
 * @createTime: 2016/8/30
 */
public class JkApiConvertFactory extends Converter.Factory{

    public static JkApiConvertFactory create() {
        return create(new Gson());
    }

    public static JkApiConvertFactory create(Gson gson) {
        return new JkApiConvertFactory(gson);
    }

    private JkApiConvertFactory(Gson gson) {
        if (gson == null) throw new NullPointerException("gson == null");
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        return new GsonResponseBodyConverter<>(type);
    }

    final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
        private final Type type;

        GsonResponseBodyConverter(Type type) {
            this.type = type;
        }

        @Override public T convert(ResponseBody value) throws IOException {
            BaseResponse baseResponse;
            String reString;
            try {
                reString = value.string();
                // 解析Json数据返回TransData对象
                TransData transData = TransUtil.getResponse(reString);
                try {
                    if (transData.getErrorcode().equals("0") &&  !TextUtils.isEmpty(transData.getInfo())) {
                        baseResponse = new Gson().fromJson(transData.getInfo(), type);
                        baseResponse.setSuccess(transData.getErrorcode().equals("0"));
                        baseResponse.setInfo(transData.getInfo());
                        baseResponse.setInfo(transData.getInfo());
                    } else {
                        baseResponse = (BaseResponse) StringUtil.getObject(((Class) type).getName());
                        baseResponse.setSuccess(transData.getErrorcode().equals("0"));
                        baseResponse.setInfo(transData.getInfo());
                        baseResponse.setInfo(transData.getInfo());
                    }
                    return (T)baseResponse;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //从不返回一个空的Response.
            baseResponse = (BaseResponse) StringUtil.getObject(((Class) type).getName());
            try {
                baseResponse.setSuccess(false);
                //JkApiConvertFactory can not recognize the response!
                baseResponse.setErrormsg("");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                return (T)baseResponse;
            }
        }
    }
}

接着我们写api接口,我这里是将对应的接口封装到对应的类中,这样当前api类中接口名称可以统一起来,请求api的方法也写入当前api类,这样做既能解耦又能减少在使用处的冗余代码,代码如下:

/**
 * @className: ApiLogin
 * @classDescription: 登陆api
 * @author: leibing
 * @createTime: 2016/8/12
 */
public class ApiLogin {
    // api
    private ApiStore mApiStore;

    /**
     * Constructor
     * @author leibing
     * @createTime 2016/08/30
     * @lastModify 2016/08/30
     * @param
     * @return
     */
    public ApiLogin() {
        // 初始化api
        mApiStore = JkApiRequest.getInstance().create(ApiStore.class);
    }

    /**
     * 登录
     * @author leibing
     * @createTime 2016/08/30
     * @lastModify 2016/08/30
     * @param username 用户名
     * @param password 密码
     * @param callback 回调
     * @return
     */
    public void Login(String username, String password, ApiCallback<LoginResponse> callback){
        Call<LoginResponse> mCall =  mApiStore.login(URLEncoder.encode(username), password);
        mCall.enqueue(new JkApiCallback<LoginResponse>(callback));
    }

    /**
     * @interfaceName: ApiStore
     * @interfaceDescription: 登录模块api接口
     * @author: leibing
     * @createTime: 2016/08/30
     */
    private interface ApiStore {
        @GET("app/User/Login")
        Call<LoginResponse> login(
                @Query("username") String username,
                @Query("userpass") String userpass);
    }
}

从上面代码我们看到ApiCallback和JkApiCallback两个回调接口,这两者区别在哪呢?观察仔细的童鞋会发现这个问题.ApiCallback接口是作为通用接口,而JkApiCallback是作为一个接口封装类,针对不同数据情景,做不同回调.

ApiCallback代码如下:

/**
 * @className: ApiCallback
 * @classDescription: Api回调
 * @author: leibing
 * @createTime: 2016/08/30
 */
public interface ApiCallback<T> {
    // 请求数据成功
    void onSuccess(T response);
    // 请求数据错误
    void onError(String err_msg);
    // 网络请求失败
    void onFailure();
}

JkApiCallback代码如下:

public class JkApiCallback<T> implements Callback <T>{
    // 回调
    private ApiCallback<T> mCallback;

    /**
     * Constructor
     * @author leibing
     * @createTime 2016/08/30
     * @lastModify 2016/08/30
     * @param mCallback 回调
     * @return
     */
    public JkApiCallback(ApiCallback<T> mCallback){
        this.mCallback = mCallback;
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (mCallback == null){
            throw new NullPointerException("mCallback == null");
        }
        if (response != null && response.body() != null){
            if (((BaseResponse)response.body()).isSuccess()){
                mCallback.onSuccess((T)response.body());
            }else {
                mCallback.onError(((BaseResponse) response.body()).getErrormsg());
            }
        }else {
            mCallback.onFailure();
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        if (mCallback == null){
            throw new NullPointerException("mCallback == null");
        }
        mCallback.onFailure();
    }
}

接下来我们写Response类,用于接收Gson解析回来的数据,这个只需写json数据信息里面的字段.代码如下:

/**
 * @className: LoginResponse
 * @classDescription: 获取登录返回的信息
 * @author: leibing
 * @createTime: 2016/08/30
 */
public class LoginResponse extends BaseResponse implements Serializable{
    // 序列化UID 用于反序列化
    private static final long serialVersionUID = 4863726647304575308L;
    // token
    public String accesstoken;
}

阅读仔细的童鞋会发现,在Convert工厂中Gson解析时,用到了一个BaseResponse,这个响应类是作为基类,就是服务端返回的固定json数据格式,因为每个项目返回的固定格式可能不一样,所以只需改这里,就能定制对应项目的网络框架.
BaseResponse代码如下:

/**
 * @className: BaseResponse
 * @classDescription: 网络请求返回对象公共抽象类
 * @author: leibing
 * @createTime: 2016/08/30
 */
public class BaseResponse implements Serializable {
    // 序列化UID 用于反序列化
    private static final long serialVersionUID = 234513596098152098L;
    // 是否成功
    private boolean isSuccess;
    // 数据
    public String info;
    // 错误消息
    public String errormsg;

    public boolean isSuccess() {
        return isSuccess;
    }

    public void setSuccess(boolean success) {
        isSuccess = success;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    public String getErrormsg() {
        return errormsg;
    }

    public void setErrormsg(String errormsg) {
        this.errormsg = errormsg;
    }
}

一个简洁、实用、易移植的网络框架模块封装完毕.

本项目已开源github,地址:a common httpRequest.

如有疑问请联系,联系方式如下:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,566评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,612评论 4 59
  • 不得不说北小武当了这个文艺委员之后,班级里面的,日常生活的确变得多姿多彩了。比如学校每天上午第二节课的眼保健操是大...
    顾小乔_f34b阅读 235评论 0 0
  • 文/然雪婵 不常出远门的父亲今年10月份去了广西桂林,与五叔同在一个城市做室内的水电安装工程。 我和弟劝了他数日,...
    然雪婵阅读 590评论 5 12
  • 凌晨四点半,巴士就陆续开来了。天还没放亮,板房区的轮廓模糊着,已经陆续有吆喝声,咒骂声,混着兴奋的笑声,哈欠声,脚...
    孟二小姐阅读 1,002评论 14 7