1. 程式人生 > >RetrofitUtils工具類

RetrofitUtils工具類


public class RetrofitUtils {
    private static RetrofitUtils retrofitUtils;
    private final OkHttpClient okHttpClient;

    /**
     * 雙重檢驗鎖
     * @return
     */
    public static RetrofitUtils getInstance() {
        if (retrofitUtils==null) {
            synchronized (RetrofitUtils.class){
                if (retrofitUtils==null) {
                    retrofitUtils=new RetrofitUtils();
                }
            }
        }
        return retrofitUtils;
    }


    private RetrofitUtils() {
        //設定日誌攔截器
        HttpLoggingInterceptor httpLoggingInterceptor=new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)//設定日誌攔截器
                .writeTimeout(5,TimeUnit.SECONDS)//寫入超時時間
                .readTimeout(5,TimeUnit.SECONDS)//讀取超時時間
                .connectTimeout(5,TimeUnit.SECONDS)//超時時間
               // .addInterceptor(new HeaderInterceptor())//頭部攔截器
                .build();
    }
    //retrofit-rxjava-rxandroid
    public <T> T createApi(String baseUrl,Class<T> cls){
        Retrofit retrofit=new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit.create(cls);
    }
}