Skip to content

Instantly share code, notes, and snippets.

@ilhamsuaib
Created March 26, 2019 13:32
Show Gist options
  • Save ilhamsuaib/dc057a29854cd3f8e76257d5e389b061 to your computer and use it in GitHub Desktop.
Save ilhamsuaib/dc057a29854cd3f8e76257d5e389b061 to your computer and use it in GitHub Desktop.
Contoh hadle expired token otomatis
class HttpInterceptor(private val context: Context) : Interceptor {
lateinit var sp: PreferencesManager
companion object {
const val TAG = "HttpInterceptor"
}
override fun intercept(chain: Interceptor.Chain?): Response {
sp = PreferencesManager(context)
i(TAG, "token : ${sp.token}")
val token = sp.token
val request = chain?.request()!!
//include token header to every request
val modifyRequest: Request? = request.newBuilder()
?.addHeader("token", token)
?.build()
val response: Response = chain.proceed(modifyRequest!!)
/*this will executed when error 401/token expired*/
if (response.code() == 401){
refreshToken() //refresh token
val newToken = sp.token //now token refreshed
d(TAG, "new token : ${sp.token}")
if (newToken.isNotEmpty()){
/*val newReqestBody = FormBody.Builder()
.add("token", newToken)
.build()*/
val newRequest: Request? = request.newBuilder()
?.addHeader("token", newToken)
?.build()
return chain.proceed(newRequest!!)
}
}
return response
}
private fun refreshToken() {
i(TAG, "old token : ${sp.token}")
/*create request to get new token
this will send old token*/
val requestBody: RequestBody = FormBody.Builder()
.add("token", sp.token)
.build()
val request = Request.Builder()
.url("${BuildConfig.BASE_URL}api/api/auth/renewtoken")
.post(requestBody)
.build()
try {
val httpClient = OkHttpClient()
val response: Response = httpClient.newCall(request).execute()
if (response.code() == 200){
val jsonData = response.body()?.string()
d(TAG, "token response : $jsonData")
val tokenResponse = Gson().fromJson(jsonData, TokenResponse::class.java)
if (tokenResponse.status!!) {
tokenResponse.data?.token?.let {
d(TAG, "new token : $it")
sp.token = it
}
}else
e(TAG, "Gagal memuat token baru, coba login kembali")
}
}catch (e: IOException){
e.printStackTrace()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment