RetrofitUtil(关于retrofit的封装工具类,可添加拦截器)

RetrofitUtil(关于retrofit的封装工具类,可添加拦截器)

import android.util.Log;

import com.example.rrtrofitrxjavamvp_demo.ApiService;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
public class RetrofitUtil {
    private static RetrofitUtil retrofitUtil;
    private Retrofit retrofit;
    private OkHttpClient client;


    private RetrofitUtil() {
        client = new OkHttpClient.Builder()
                .addInterceptor(new LogInterceptor())
                .connectTimeout(5000, TimeUnit.MICROSECONDS)
                .build();
    }

    public static RetrofitUtil getInstance() {
        if (null == retrofitUtil) {
            synchronized (RetrofitUtil.class) {
                if (null == retrofitUtil) {
                    retrofitUtil = new RetrofitUtil();
                }
            }
        }
        return retrofitUtil;
    }

    public ApiService getApiService(String baseURL) {
        retrofit = new Retrofit.Builder()
                .client(client)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseURL)
                .build();
        ApiService service = retrofit.create(ApiService.class);
        return service;
    }

    //拦截器
    class LogInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            //请求对象
            Request request = chain.request();
            String method = request.method();
            HttpUrl url = request.url();
            Log.d("LogInterceptor", method + "===" + url);
            //返回的响应对象
            Response proceed = chain.proceed(request);

            return proceed;
        }
    }
}

你可能感兴趣的:(RetrofitUtil(关于retrofit的封装工具类,可添加拦截器))