Retrofit工具类的封装

来源:互联网 发布:验证码java 编辑:程序博客网 时间:2024/06/02 01:19
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;    }}