1.添加依赖
implementation 'com.squareup.okhttp3:okhttp:3.2.0'
implementation 'com.squareup.okio:okio:1.7.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.retrofit2:retrofit:2.0.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
2.封装工具类
public class RetrofitUtils {
private static RetrofitUtils retrofitUtils;
private RetrofitUtils(){}
public static RetrofitUtils getInstance(){
if (retrofitUtils==null){
synchronized (RetrofitUtils.class){
if (retrofitUtils==null){
retrofitUtils=new RetrofitUtils();
}
}
}
return retrofitUtils;
}
private static OkHttpClient okHttpClient;
private static synchronized OkHttpClient getOkHttpClient() {
final HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.i("xxx",message);
}
});
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient = new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.addHeader("userId", "11249")
.addHeader("sessionId", "155056366467311249")
.build();
return chain.proceed(request);
}
})
.build();
return okHttpClient;
}
private static Retrofit retrofit;
public static synchronized Retrofit getRetrofit(String ShowUrl){
retrofit=new Retrofit.Builder()
.baseUrl(ShowUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(getOkHttpClient())
.build();
return retrofit;
}
public <T> T getApiService(String ShowUrl,Class<T> service){
Retrofit retrofit=getRetrofit(ShowUrl);
T t=retrofit.create(service);
return t;
}
}