Skip to content

Instantly share code, notes, and snippets.

@Sanjay-Prajapati
Last active January 8, 2019 10:27
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sanjay-Prajapati/5c592f6f360fe5fe39927bbc39da70e4 to your computer and use it in GitHub Desktop.
Save Sanjay-Prajapati/5c592f6f360fe5fe39927bbc39da70e4 to your computer and use it in GitHub Desktop.
Retrofit2 custom interceptor that parse the response from API. After that we can check status and based on that returns a same copy that other classes can consume.
import com.google.gson.Gson
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import org.json.JSONException
/**
* Logout Interceptor.
* Here i extend the BaseActivity to navigate user to another screen. i need runOnUIThread to execute navigateToLogin() method.
*/
class LogoutInterceptor : BaseActivity(), Interceptor {
override fun intercept(chain: Interceptor.Chain?): Response {
val response: Response = chain?.proceed(chain.request())!!
val globJson = response.body()!!.string()
try {
/**
* GlobalResponse class is the API response model.
* status is the class member of GlobalResponse class. we will get logout session code in status.
* SessionInvalid variable contains the defined status code.
*/
val globalResponse: GlobalResponse = Gson().fromJson(globJson, GlobalResponse::class.java)
if (globalResponse.status == SessionInvalid) {
runOnUiThread(object : Runnable {
override fun run() {
navigateToLogin()
/**
navigateToLogin() method's body part is defined in BaseActivity. Here AppApplication is Application class
val intent = Intent(AppApplication.instance.applicationContext, WelcomeActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
intent.putExtra(SESSION_LOGOUT_REASON, true)
AppApplication.instance.startActivity(intent)
*/
}
})
}
} catch (e: JSONException) {
e.printStackTrace()
}
// Re-create the response before returning it because body can be read only once
return response.newBuilder()
.body(ResponseBody.create(response.body()!!.contentType(), globJson)).build()
}
}
/**
* You can call your Custom interceptor while creating OkHttpClient object
**/
val okHttp:OkHttpClient= OkHttpClient.Builder()
.....
.addNetworkInterceptor(LogoutInterceptor())
....
.build()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment