Read the original article:Understanding Interceptors in Network Requests
Introduction
This example answers the question of how to manage advanced network communication using ArkTS on the HarmonyOS platform. The application fetches a list of users, caches this data, and dynamically changes the requested URL based on network quality. This way, both data usage is optimized and the user experience is improved.
Why Do We Use Interceptors?
Network conditions in mobile applications are variable, and managing data requests according to these conditions is important. When the network is slow, large data requests can cause the app to lag or freeze. Additionally, repeatedly downloading the same data leads to unnecessary resource consumption.
The interceptor structure allows us to intervene in requests and responses to solve these problems. Thus, the request URL can be dynamically changed, responses can be cached, and repeated network calls can be prevented.
The Role of Interceptors in the Project
ResponseCachingInterceptor:
Caches responses for identical requests made before. Therefore, for repeated requests, no network call is made and results are returned quickly from the cache. This increases performance and prevents unnecessary data usage.
RequestUrlChangeInterceptor:
Activates when the network is slow. It reduces the results parameter in the request URL to fetch less data. This helps preserve device resources and prevents users from having to wait too long.
Implementation
First, we need to create a way to cache network responses so that repeated requests to the same URL don’t trigger unnecessary network traffic. To achieve this, we define a ResponseCache class that stores responses in a simple object keyed by URL strings.
class ResponseCache {
private readonly cache: Record<string, rcp.Response> = {};
getResponse(url: string): rcp.Response {
return this.cache[url];
}
setResponse(url: string, response: rcp.Response): void {
this.cache[url] = response;
}
}
After having a cache, we create an interceptor class called ResponseCachingInterceptor. This interceptor intercepts every network request and first checks if there is a cached response for the requested URL. If it exists, the interceptor returns the cached response immediately without making a network call. Otherwise, it proceeds to make the network request, then caches the response once received.
class ResponseCachingInterceptor implements rcp.Interceptor {
private readonly cache: ResponseCache;
constructor(cache: ResponseCache) {
this.cache = cache;
}
async intercept(context: rcp.RequestContext, next: rcp.RequestHandler): Promise<rcp.Response> {
const url = context.request.url.href;
const responseFromCache = this.cache.getResponse(url);
if (responseFromCache) {
return Promise.resolve(responseFromCache);
}
const promise = next.handle(context);
promise.then((resp) => {
resp.statusCode;
this.cache.setResponse(url, resp);
});
return promise;
}
}
Next, we want to adapt requests based on the network quality. For this, we create a NetworkQualityProvider class that stores the current network speed status. Using this, we build another interceptor called RequestUrlChangeInterceptor.
This interceptor listens to outgoing GET requests. If it detects a slow network connection, it modifies the request URL by reducing the number of requested results (for example, lowering results=5 to results=2). This helps optimize data usage and speed on poor connections.
export class NetworkQualityProvider {
isNetworkFast: boolean = true;
public constructor(isNetworkFast: boolean) {
this.isNetworkFast = isNetworkFast;
}
}
export class RequestUrlChangeInterceptor implements rcp.Interceptor {
private readonly networkQualityProvider: NetworkQualityProvider;
constructor(networkQualityProvider: NetworkQualityProvider) {
this.networkQualityProvider = networkQualityProvider;
}
async intercept(context: rcp.RequestContext, next: rcp.RequestHandler): Promise<rcp.Response> {
if (context.request.method === 'GET' && !this.networkQualityProvider.isNetworkFast) {
console.log('[RequestUrlChangeInterceptor]: Slow network detected, modifying request URL');
let urlString = context.request.url.href;
urlString = urlString.replace(/results=\d+/, 'results=2');
context.request.url = url.URL.parseURL(urlString);
} else {
console.log('[RequestUrlChangeInterceptor]: Network is fast, request unchanged');
}
return next.handle(context);
}
}
Finally, to use these interceptors together, we create a ResponseCache instance and a NetworkQualityProvider with the current network status. We then create a network session, passing these interceptors in the order we want them to run. The caching interceptor will check for cached responses first, and the URL changing interceptor will modify requests if needed based on network quality.
const cache = new ResponseCache();
const networkQualityProvider = new NetworkQualityProvider(false); // false simulates slow network
const session = rcp.createSession({
interceptors: [
new ResponseCachingInterceptor(cache),
new RequestUrlChangeInterceptor(networkQualityProvider)
]
});
This structure makes data fetching efficient by reusing cached responses and adapts requests according to slow network conditions to prevent performance degradation.
Conclusion
This example shows how to smartly and efficiently manage network requests using HarmonyOS and ArkTS. Thanks to interceptors, the app adapts to network speed, reduces unnecessary data usage, and gains speed through caching. This approach offers a significant technical advantage for modern mobile application development.

Top comments (0)