public class RetrofitUtils { private static RetrofitUtils retrofitUtils=null; private OkHttpClient okHttpClient; public static RetrofitUtils newInstance(){ if(retrofitUtils==null){ synchronized(RetrofitUtils.class){ if(retrofitUtils==null){ retrofitUtils=new RetrofitUtils(); } } } return retrofitUtils; } //构造方法 添加okhttpclient public RetrofitUtils(){ //缓存目录 File sdcache = new File(Environment.getExternalStorageDirectory(), "cache"); int cacheSize = 10 * 1024 * 1024; //OkHttp3拦截器 HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() { @Override public void log(String message) { Log.i("xxx", message.toString()); } }); //Okhttp3的拦截器日志分类 4种 httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); okHttpClient = new OkHttpClient.Builder().connectTimeout(15, TimeUnit.SECONDS) //添加OkHttp3的拦截器 .addInterceptor(httpLoggingInterceptor) .writeTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS) .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize)) .build(); } //创建retrofitservice类 public RetrofitService create(Class<RetrofitService> retrofitService, String baseurl){ Retrofit retrofit = new Retrofit.Builder() .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(baseurl) .client(okHttpClient) .build(); RetrofitService service = retrofit.create(retrofitService); return service; } }
Retrofit工具类的封装
最新推荐文章于 2020-03-21 15:53:05 发布