retrofit+rxjava的解析工具类

public class RetrofitUtils {

    private static final long DEFAULT_TIMEOUT = 20000;


    private static volatile ApiService mApiService;

    public static ApiService getService() {

        if (mApiService == null) {
            synchronized (RetrofitUtils.class) {
                if (mApiService == null) {
                    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
                    if (BuildConfig.DEBUG) {
                        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
                    } else {
                        logging.setLevel(HttpLoggingInterceptor.Level.NONE);
                    }


                    OkHttpClient httpClient = new OkHttpClient.Builder()
                            .addInterceptor(logging)
                            .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                            .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                            .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                            .build();

                    Retrofit retrofit = new Retrofit.Builder()
                            .client(httpClient)
                            //          new Retrofit2ConverterFactory()        GsonConverterFactory.create()
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .baseUrl(ApiService.url)
                            .build();
                    mApiService = retrofit.create(ApiService.class);
                }
            }
        }
        return mApiService;
    }

}

解释:
ApiService --------你自己写的api接口
HttpLoggingInterceptor -----日志拦截器,需要导入依赖
工具类需要的依赖有:

//拦截器
implementation 'com.squareup.okhttp3:logging-interceptor:3.12.'
//RXJava:
 implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0' // 必要依赖,和Rxjava结合必须用到,下面会提到
	implementation "io.reactivex.rxjava2:rxjava:2.1.3" // 必要rxjava2依赖
   	 implementation "io.reactivex.rxjava2:rxandroid:2.0.1" // 必要rxandrroid依赖,切线程时需要用到

//OkHttp网络解析
	implementation 'com.squareup.okhttp3:okhttp:3.2.0'
	implementation 'com.squareup.okio:okio:1.7.0'

//Retrofit网络解析
	implementation 'com.squareup.retrofit2:retrofit:2.3.0'
	implementation 'com.squareup.retrofit2:converter-gson:2.1.0'

你可能感兴趣的:(retrofit+rxjava的解析工具类)