基于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.

如有疑問請聯系,聯系方式如下:

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,284評論 25 708
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,232評論 4 61
  • 不得不說北小武當了這個文藝委員之后,班級里面的,日常生活的確變得多姿多彩了。比如學校每天上午第二節課的眼保健操是大...
    顧小喬_f34b閱讀 262評論 0 0
  • 文/然雪嬋 不常出遠門的父親今年10月份去了廣西桂林,與五叔同在一個城市做室內的水電安裝工程。 我和弟勸了他數日,...
    然雪嬋閱讀 658評論 5 12
  • 凌晨四點半,巴士就陸續開來了。天還沒放亮,板房區的輪廓模糊著,已經陸續有吆喝聲,咒罵聲,混著興奮的笑聲,哈欠聲,腳...
    孟二小姐閱讀 1,056評論 14 7