美文网首页安卓开发博客程序员Android...
三步Retrofit2+RxJava2+OkHttp3网络请求封

三步Retrofit2+RxJava2+OkHttp3网络请求封

作者: 雪糕的粑粑 | 来源:发表于2017-06-28 17:16 被阅读0次

    今天来分享一下Retrofit2+RxJava2+OkHttp3的封装。

    第一步 - 那自然是引用相关的库:

       compile 'com.squareup.retrofit2:retrofit:2.3.0'
       compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
       // gson解析,可以自行替换
       compile 'com.squareup.retrofit2:converter-gson:2.3.0'
       compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
      // 日志的拦截器,也可以自行选择
       compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
       compile 'io.reactivex.rxjava2:rxjava:2.0.1'
       compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    

    第二步,我们在Application创建一个OkHttpClient:

    public class MyApplication extends Application {
        private static final int TIMEOUT_READ = 15;
        private static final int TIMEOUT_CONNECTION = 15;
        private static OkHttpClient mOkHttpClient;
    
    public OkHttpClient genericClient() {
    
            if (mOkHttpClient != null)
                return mOkHttpClient;
    
            HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();
            HttpLoggingInterceptor.Level level = BuildConfig.IS_DEBUG ?
                    HttpLoggingInterceptor.Level.HEADERS :
                    HttpLoggingInterceptor.Level.NONE;
            logInterceptor.setLevel(level);
    
            return mOkHttpClient = new OkHttpClient.Builder()
                    .retryOnConnectionFailure(true)
                    .addInterceptor(logInterceptor)
                    .addNetworkInterceptor(new CacheInterceptor())
                    .readTimeout(TIMEOUT_READ, TimeUnit.SECONDS)
                    .connectTimeout(TIMEOUT_CONNECTION, TimeUnit.SECONDS)
                    .build();
        }
    
    }
    

    创建好了,先放着等后面需要使用。

    第三步,创建一个BaseApi类:

    该类有两个主要职责,1.负责创建Retrofit的实例;2.执行网络请求。

    public class BaseApi {
      // 创建网络接口请求实例
      public static <T> T createApi(Class<T> service) {
            final String url = KEY_BASE_URL;
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .addConverterFactory(GsonConverterFactory.create())
                     // 注意这里使用了刚才在application里提供创建okhttp的方法
                    .client(MyApplication.getApplication().genericClient())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
            return retrofit.create(service);
        }
    
     // 执行网络请求
     public static <T> void request(Observable<T> observable,
                                       final IResponseListener<T> listener) {
    
            if (!NetUtils.isConnected(MyApplication.getApplication())) {
                ToastUtils.getInstance().showToast("网络不可用,请检查网络");
                if (listener != null) {
                    listener.onFail();
                }
                return;
            }
            observable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<T>() {
    
                                   @Override
                                   public void onError(Throwable e) {
                                       e.printStackTrace();
                                       LogUtils.d("onError", e.getMessage());
                                       if (listener != null) {
                                           listener.onFail();
                                       }
                                   }
    
                                   @Override
                                   public void onComplete() {
    
                                   }
    
                                   @Override
                                   public void onSubscribe(Disposable disposable) {
    
                                   }
    
                                   @Override
                                   public void onNext(T data) {
                                       if (listener != null) {
                                           listener.onSuccess(data);
                                       }
                                   }
                               }
                    );
    
        public interface IResponseListener<T> {
            void onSuccess(T data);
            void onFail();
        }
    }
    

    这样一个封装就完成了,下面我用demo来测试一下效果:

    public class MainActivity extends AppCompatActivity {
    
        private TextView tvTest;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            tvTest = (TextView) findViewById(R.id.tv_test);
    
            BaseApi.request(BaseApi.createApi(IServiceApi.class).getBookInfo(),
                    new BaseApi.IResponseListener<Book>() {
                        @Override
                        public void onSuccess(Book data) {
                            tvTest.setText(data.summary);
                        }
    
                        @Override
                        public void onFail() {
    
                        }
                    });
        }
    }
    

    效果就不演示了,放出 demo大家可以下载看看。

    相关文章

      网友评论

        本文标题:三步Retrofit2+RxJava2+OkHttp3网络请求封

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