Good evening everyone! I want to use shared preferences to store my token(I know that this is not secure, I am new in android development and just want to try) and then pass it to the interceptor. How can I initialize shared preferences there? Thank you! Or can you give me a tips how I can implement interceptor or store token.
Sorry, I already tried to search for this topic, and was not able to implement methods of other developers.
object NetworkModule {
var sharedPreferences = //GET SHARED PREFERENCES THERE
var authToken: String? = sharedPreferences.getString("Token", null)
val baseURL = //my base url
val loggingInterceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
var httpClient = OkHttpClient.Builder().addInterceptor { chain ->
chain.proceed(
chain.request().newBuilder().also { it.addHeader("Authorization", "Bearer $authToken") }
.build()
)
}.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.addNetworkInterceptor(loggingInterceptor)
.build()
val retrofit = Retrofit.Builder().baseUrl(baseURL).addConverterFactory(
GsonConverterFactory.create()
).client(httpClient).build()
val api: API by lazy { retrofit.create() }
val apiClient = ApiClient(api)
}