增加請求頭的Retorfit封裝
阿新 • • 發佈:2019-01-09
public class RetrofitUtils { private static volatile RetrofitUtils instance; private final Retrofit retrofit; private RetrofitUtils(){ OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new Logger()).build(); retrofit = new Retrofit.Builder() .client(client) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl("http://120.27.23.105/") .build(); } public static RetrofitUtils getInstance(){ if(instance==null){ synchronized (RetrofitUtils.class){ if(instance==null){ instance=new RetrofitUtils(); } } } return instance; } public ApiService getApiService(){ ApiService apiService = retrofit.create(ApiService.class); return apiService; } class Logger implementsInterceptor { @Override public Response intercept(Chain chain) throws IOException { Request original = chain.request(); HttpUrl url=original.url().newBuilder() .addQueryParameter("source","android") .build(); //新增請求頭 Request request = original.newBuilder() .url(url) .build(); return chain.proceed(request); } } }