使用登录名和密码,我向服务器发出请求,作为响应,我收到一个令牌,我将其保存在SharedPreferences
. 之后,我转到另一个屏幕并尝试请求数据,但由于令牌丢失,我得到了 401。只有在应用程序重新启动后SharedPreferences
才会更新in 的值。NetworkModule
我需要在应用程序的当前启动中获取它并在授权后立即执行请求。所以我将实例传递SharedPreferences
给AuthInterceptor
.
val sharedPreferencesModule = module {
single { androidApplication().getSharedPreferences(sharedPreferences, Context.MODE_PRIVATE) }
}
val networkModule = module {
fun provideRetrofit(factory: Gson, client: OkHttpClient, sharedPreferences: SharedPreferences): Retrofit {
val logging = if (BuildConfig.DEBUG) {
HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
} else {
HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC)
}
return Retrofit.Builder()
.baseUrl(BuildConfig.SERVER_URL)
.addConverterFactory(GsonConverterFactory.create(factory))
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.client(
client.newBuilder()
.addInterceptor(logging)
.addInterceptor(AuthInterceptor(sharedPreferences.getString("auth_token","")))
.build()
)
.build()
}
single {
provideRetrofit(
get(),
get(),
androidApplication()
.getSharedPreferences(
sharedPreferences,
Context.MODE_PRIVATE
)
)
}
}
class AuthInterceptor(var token: String? = null) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val authHeader = chain.request().header("Authorization")
val request: Request = if (authHeader.isNullOrEmpty() && !token.isNullOrEmpty()) {
chain.request().newBuilder()
.addHeader("Authorization", "Bearer $token")
.build()
} else {
chain.request()
}
return chain.proceed(request)
}
}