Android Retrofit OkHttp RxJava集成及简单封装

1.添加gradle依赖

    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
    implementation 'com.squareup.okio:okio:2.0.0'
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'

2.创建HttpParamInterceptor(OkHttp拦截器)
由于项目中网络请求有公共参数,所以再拦截器做了统一处理

   @Override
   public Response intercept(Chain chain) throws IOException {
       Request oldRequest = chain.request();
       Request.Builder newRequestBuild = oldRequest.newBuilder();
       String method = oldRequest.method();
       FormBody newFormBody = null;
       if("POST".equals(method)) {
           RequestBody oldBody = oldRequest.body();
           if (oldBody instanceof FormBody) {
               FormBody oldFromBody = (FormBody)oldBody;
               FormBody.Builder formBodyBuilder = new FormBody.Builder();
               int size = oldFromBody.size();
               TreeMap treeMap = new TreeMap<>();
               for (int i = 0; i < size; i++) {
                   String name = oldFromBody.name(i);
                   String value = oldFromBody.value(i);
                   treeMap.put(name, value);
                   formBodyBuilder.add(name, value);
               }
               injectCommonParams(formBodyBuilder, treeMap);
               String sign = Util.getSign(treeMap);
               formBodyBuilder.add("sign", sign);
               newFormBody = formBodyBuilder.build();
           }
       }
       if (newFormBody != null) newRequestBuild.post(newFormBody);
       Request request = newRequestBuild.build();
       return chain.proceed(request);
   }

injectCommonParams方法如下

    private void injectCommonParams(FormBody.Builder formBodyBuilder, TreeMap treeMap) {
        String userToken = PhoneBaseUtil.getShareData(ZZApplication.getIns(), Constant.PublicConstant.USERTOKEN);
        if(!TextUtils.isEmpty(userToken)){
            treeMap.put("userToken", userToken);
            formBodyBuilder.add("userToken", userToken);
        }
        String nonce = "-" + RandomUtils.generateStringInNumber(10);
        String timestamp = "-" + DateUtils.dataOne(DateUtils.getCurrentTime_Today());
        treeMap.put("nonce", nonce);
        formBodyBuilder.add("nonce", nonce);
        treeMap.put("timestamp", timestamp);
        formBodyBuilder.add("timestamp", timestamp);
    }

由于项目要求需要将所以参数按ASCII码排序,用到了treeMap.
3.创建RetrofitManager 复制初始化,创建service及订阅
3.1初始化

      OkHttpClient.Builder builder = new OkHttpClient.Builder();
      //连接 超时时间
      builder.connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS);
      //写操作 超时时间
      builder.writeTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS);
      //读操作 超时时间
      builder.readTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS);
      //错误重连
      builder.retryOnConnectionFailure(true);
      //add http post common param
      builder.addInterceptor(new HttpParamInterceptor());
      HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
      logging.setLevel(HttpLoggingInterceptor.Level.BODY);
      //add log interceptor
      builder.addInterceptor(logging);
      okHttpClient = builder.build();

      retrofit = new Retrofit.Builder().baseUrl(SERVER_URL)
              .addConverterFactory(GsonConverterFactory.create())
              .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
              .client(okHttpClient)
              .build();

3.2 创建service

public static  T create(Class service){
        return retrofit.create(service);
    }

3.3 订阅

public static  void toSubscribe(Observable o, BaseObserver observer) {
        o.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())

                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

BaseResponse

    private int Code;
    private String Msg;

4.BaseObserver封装
下面贴出关键代码

public abstract class BaseObserver implements Observer{
    @Override
    public void onSubscribe(Disposable d) {
        onRequestStart();
    }

    @Override
    public void onNext(T result) {
        if (result.getCode() == 1) {//根据实际接口定义值修改
            onSuccess(result);
        } else {
            showErrCodeMsg(result.getCode(), result.getMsg());
            onFailed(result.getCode(), result.getMsg());
        }
    }

    @Override
    public void onError(Throwable e) {
        //代码过长影响阅读未粘出
    }

    @Override
    public void onComplete() {
        onRequestEnd();
    }

    public abstract void onSuccess(T result);

    public abstract void onFailed(int code, String msg);

    private void onRequestStart() {
        if(mContext != null){
            if(mLoadingDialog == null){
                mLoadingDialog = new LoadingDialog(mContext);
            }
            if(mContext instanceof Activity && !((Activity) mContext).isFinishing()) {
                mLoadingDialog.show();
            }
        }
    }

    private void onRequestEnd() {
        if(mLoadingDialog != null && mLoadingDialog.isShowing()){
            mLoadingDialog.dismiss();
        }
    }

    protected void showErrCodeMsg(int code, String msg){
        ToastUtils.showToast(msg);
    }
}

5.调用实例

RetrofitManager.toSubscribe(RetrofitManager.create(AnswerService.class).reportError(qid, type, desc), new BaseObserver(this) {
            @Override
            public void onSuccess(BaseResponse result) {
                LogUtils.d(GsonUtils.toJson(result));
                ToastUtils.showToast(ReportErrorActivity.this, getString(R.string.answer_err_submit_success));
                finish();
            }

            @Override
            public void onFailed(int code, String msg) {
                LogUtils.e(msg);
            }
        });

AnswerService

    @FormUrlEncoded
    @POST("qqqqqq/xxxxxx")
    Observable reportError(@Field("qid") String qid, @Field("type") String type, @Field("content") String content);

6.总结
项目使用了retrofit使接口变得更加整洁清晰,rxjava也使代码逻辑变得清晰。本篇文章简单得介绍了框架的使用及封装,有不足之处请多提宝贵建议.

你可能感兴趣的:(Android Retrofit OkHttp RxJava集成及简单封装)