在公司组件化开发中,让我很头疼的就是网络层的交互了,由于历史原因,我们的网络封装与业务耦合度很高,拆分起来比较头疼,没办法,既然要做组件化,只能耐着性子慢慢拆分。
切入正题,我们的项目网络请求使用的是RxJava2+Retrofit2+Okhttp,为了将网络模块单独抽出来以适应三个端的调用,就得让网络层与业务层完全隔离。
这里介绍我目前对网络层简单实用的封装,网络请求就一个类Httpclient:
/*** 网络请求封装类* =============================* 使用:* new HttpClient.Builder()* .baseUrl(..)* .url(..)* .interceptor(..)* .listener(..)* .build()* .request(BaseApi);* ================================** Created by huolala-sunyan on 2018/8/15.*/
public class HttpClient {private static OkHttpClient mOkHttpClient ;private String baseUrl;private OnHttpResultListener listener;private int retryCount = 3; //retry次数private int retryDelay = 3000; //retry延迟private int retryIncreaseDelay = 3000; //retry叠加private HttpClient(String baseUrl, Interceptor interceptor, OnHttpResultListener listener ,int retryCount ,int retryDelay , int retryIncreaseDelay){this.baseUrl = baseUrl;this.listener = listener;this.retryCount = retryCount;this.retryDelay = retryDelay;this.retryIncreaseDelay = retryIncreaseDelay;OkHttpClient.Builder b = new OkHttpClient.Builder();b.readTimeout(20, TimeUnit.SECONDS);b.connectTimeout(20, TimeUnit.SECONDS);//加调试用if (BuildConfig.DEBUG)b.addNetworkInterceptor(new StethoInterceptor());if (interceptor != null