TokenInterceptor.class
public OkHttpClient getClients(Context context) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
SharedPreferences preferences = context.getSharedPreferences("logged", MODE_PRIVATE);
String tokens = preferences.getString("token", "");
return new OkHttpClient
.Builder()
.addInterceptor(interceptor)
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder()
.header("Accept", "application/json")
.header("xc-auth", ""+tokens)
.build();
return chain.proceed(request);
}
})
.readTimeout(90, TimeUnit.SECONDS)
.writeTimeout(90, TimeUnit.SECONDS)
.connectTimeout(90, TimeUnit.SECONDS)
.retryOnConnectionFailure(false)
.cache(null)
.build();
}
ApiClient.class
public static Retrofit getClient() {
OkHttpClient client = new TokenInterceptor().getClients();
if (retrofit == null) {
Gson gson = new GsonBuilder().setLenient()
.create();
retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
MainActivity.class
一个二个一个一个
1条答案
按热度按时间7lrncoxx1#
更改为
ApiClient.java
,如下所示:转换为
MainActivity.java
,如下所示: