全局网络请求工具类

**
 * Created by Administrator on 2019/3/22 0022.
 * 全局联网工具类,统一使用(单例模式)
 */

public class RetrofitUtils {

    /*
     * "http:你的本地URL本地
     * "http:你的测试URL"测试
     * "https:你的上线URL"上线
     */

//        private final String BASE_URL = "https:你的上线URL";
        //  private final String BASE_URL = "http:你的测试URL";
             private final String BASE_URL = "http:你的本地URL";


        private volatile static RetrofitUtils mRetrofitUtils;//volatile保证内存可见性、禁止指令重排
        private Retrofit mRetrofit;

        private RetrofitUtils() {

            initRetrofit();
        }

        public static RetrofitUtils getInstance() {
            if (mRetrofitUtils == null) {
                //synchronized关键字能够保证在同一时刻最多只有一个线程执行该段代码
                synchronized (RetrofitUtils.class) {
                    if (mRetrofitUtils == null) {
                        mRetrofitUtils = new RetrofitUtils();
                    }
                }
            }
            return mRetrofitUtils;
        }


        private void initRetrofit() {

             //拦截器的使用
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    try {
                        String msg = URLDecoder.decode(message, "utf-8");
                        Log.i("OkHttpInterceptor-----", msg);

                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                        Log.i("OkHttpInterceptor-----", message);
                    }
                }
            });
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        /*okhttp默认时间10秒 请求时间较长时,重新设置下  */
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.connectTimeout(15, TimeUnit.SECONDS);
            builder.readTimeout(15, TimeUnit.SECONDS);
            builder.writeTimeout(15, TimeUnit.SECONDS);
            builder.retryOnConnectionFailure(true);
            OkHttpClient client = builder.build();
            mRetrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(client)
                    .build();
        }

       //通过泛型使用接口
        public <T> T getApiServier(Class<T> reqServer) {
            return mRetrofit.create(reqServer);
        }
}

猜你喜欢

转载自blog.csdn.net/qq_38287890/article/details/88735039