美文网首页Android专题Android 开发模式和优秀框架那些事网络
基于 Retrofit、OkHttp、Gson 封装通用网络框架

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

作者: Android高级工程师 | 来源:发表于2019-05-13 16:17 被阅读45次

    背景

    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 create(Class 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 responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
            return new GsonResponseBodyConverter<>(type);
        }
    
        final class GsonResponseBodyConverter implements Converter {
            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 callback){
            Call mCall =  mApiStore.login(URLEncoder.encode(username), password);
            mCall.enqueue(new JkApiCallback(callback));
        }
    
        /**
         * @interfaceName: ApiStore
         * @interfaceDescription: 登录模块api接口
         * @author: leibing
         * @createTime: 2016/08/30
         */
        private interface ApiStore {
            @GET("app/User/Login")
            Call 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 {
        // 请求数据成功
        void onSuccess(T response);
        // 请求数据错误
        void onError(String err_msg);
        // 网络请求失败
        void onFailure();
    }
    

    JkApiCallback代码如下:

    public class JkApiCallback implements Callback {
        // 回调
        private ApiCallback mCallback;
    
        /**
         * Constructor
         * @author leibing
         * @createTime 2016/08/30
         * @lastModify 2016/08/30
         * @param mCallback 回调
         * @return
         */
        public JkApiCallback(ApiCallback mCallback){
            this.mCallback = mCallback;
        }
    
        @Override
        public void onResponse(Call call, Response 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 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;
        }
    }
    

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

    喜欢点击+关注哦

    相关文章

      网友评论

        本文标题:基于 Retrofit、OkHttp、Gson 封装通用网络框架

        本文链接:https://www.haomeiwen.com/subject/lfjhaqtx.html