Http Interceptor
The interceptor is the portal when making a request to the server using the http protocol.
When we work client side we always deal with interceptors. As a software developer we know what interceptors are, but most people can’t use them properly.
Interceptors are middleware that allows common patterns around retrying, caching, logging, and authentication to be abstracted away from individual requests.
This interceptor is usually a derivative function of the http client library that we use. for example if we work as an Android Developer http client library commonly used is Okhttp, in IOS there is Alamofire, in node.js there is axios, in flutter there is Dio, and other http client libraries.
You can use interceptors to implement a variety of common patterns, such as:
- Adding authentication headers to outgoing requests to a particular API.
- Retrying failed requests with exponential backoff.
- Caching responses for a period of time, or until invalidated by mutations.
- Customizing the parsing of responses.
- Measuring server response times and log them.
- Driving UI elements such as a loading spinner while network operations are in progress.
- Collecting and batch requests made within a certain timeframe.
- Automatically failing requests after a configurable deadline or timeout.
- Regularly polling the server and refreshing results.
Example:
Get Code September’s stories in your inbox
Join Medium for free to get updates from this writer.
Flutter Dio
class MapGoogleNetworkInterceptor extends Interceptor {
MapGoogleNetworkInterceptor({
required this.sessiontoken,
required this.key,
this.iosBundleId,
this.androidPackage,
this.androidCert,
});
final String sessiontoken;
final String key;
final String? iosBundleId;
final String? androidPackage;
final String? androidCert;
@override
void onRequest(
RequestOptions options, RequestInterceptorHandler handler) async {
options.queryParameters["sessiontoken"] = sessiontoken;
options.queryParameters["key"] = key;
if (Platform.isAndroid) {
options.headers["X-Android-Package"] = androidPackage;
options.headers["X-Android-Cert"] = androidCert;
} else if (Platform.isIOS) {
options.headers["X-Ios-Bundle-Identifier"] = iosBundleId;
}
return handler.next(options);
}
@override
void onError(DioException err, ErrorInterceptorHandler handler) {
return handler.next(err);
}
@override
void onResponse(Response response, ResponseInterceptorHandler handler) async {
return handler.next(response);
}
}
Kotlin Okhttp
class NetworkInterceptor(private val pref: Preference) : Interceptor {
private val urlsExceptionAuthorization = arrayOf(LOGIN, LOGIN_SOCMED, REGISTER)
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val originRequest = chain.request()
val requestWithUserAgent = originRequest.newBuilder().apply {
val endPoint = getEndPoint(originRequest.url.toString())
if (endPoint !in urlsExceptionAuthorization) {
header("Authorization", token)
val refTypeAvailable = originRequest.header("ref-type")
header("ref-type", refTypeAvailable ?: refType)
}
if (originRequest.method == "GET") {
header("Content-Type", "application/json")
header("Accept", "application/json")
}
header("is-mobile", "true")
header("Device-Os", "Android")
header("Os-Type", versionOS())
header("device-brand", Build.BRAND)
header("device-model", Build.MODEL)
header("App-Version", BuildConfig.VERSION_NAME)
header("Build-Number", BuildConfig.VERSION_CODE.toString())
}.build()
return chain.proceed(requestWithUserAgent)
}
private fun getEndPoint(url: String?): String {
val uri = Uri.parse(url)
return uri.path.toString().replace(API_VERSION, "")
}
private fun getSession(): SignIn {
val data: String? = pref.getString(Constants.SESSION)
return if (data != null) {
SystemUtil.gsonBuilder().fromJson(data, SignIn::class.java)
} else {
SignIn()
}
}
private val token get() = Constants.BEARER.format(getSession().token)
private val refType get() = getSession().refType.orEmpty()
private fun versionOS(): String {
return when (val level = Build.VERSION.SDK_INT) {
16 -> "Jelly Bean"
17 -> "Jelly Bean MR1"
18 -> "Jelly Bean MR2"
19 -> "Kitkat"
20 -> "Kitkat Watch"
else -> return "Android API Level: $level"
}
}
}Swift Alamofire
public class MyInterceptor: RequestInterceptor{
let userDefault: UserDefaultService
private let urlsRequiringToken: Set<String> = [
MyApiStatic.signInPath
]
public init(userDefault: UserDefaultService) {
self.userDefault = userDefault
}
public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
var modifiedRequest = urlRequest
if(needsToken(for: urlRequest.url)){
if let signIn = userDefault.getSession() {
if let token = signIn.token {
modifiedRequest.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
}
}
modifiedRequest.addValue("application/json", forHTTPHeaderField: "Accept")
modifiedRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
completion(.success(modifiedRequest))
}
public func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
completion(.doNotRetry)
}
private func needsToken(for url: URL?) -> Bool {
guard let url = url else { return false }
return urlsRequiringToken.contains(url.path)
}
}With this Interceptor, the benefit I feel when using interceptors is that it reduces the writing of repeated parameters in each request, if there is an addition to the global request parameter, I only need to change it in one class.





