Sahar Sahar - 2 years ago 123
Android Question

Cache Specific responses using retrofit

I am using retrofit2 to cash responses using cache interceptor but i want to cache specifce requests not all of it so i do the following.
I define my api as:

public interface ExampleApi {
@GET("home/false")
@Headers("MyCacheControl: public, max-age=60000")
Observable<ExampleModel> getDataWithCache();

@GET("hello")
@Headers("MyCacheControl: no-cache")
Observable<ExampleModel> getDataWithoutCache();
}


then my interceptors are:

public class OfflineResponseInterceptor implements Interceptor {

// tolerate 4-weeks stale
private static final int MAX_STALE = 60 * 60 * 24 * 28;
private final Context context;

public OfflineResponseInterceptor(Context context) {
this.context = context;
}

@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();

if (!NetworkUtil.isConnected(context)) {
request = request.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", "public, only-if-cached, max-stale=" + MAX_STALE)
.build();
}

return chain.proceed(request);
}
}


and

public class OnlineResponseInterceptor implements Interceptor {

@Override
public Response intercept(Chain chain) throws IOException {

Request request = chain.request();
String cacheControl = request.header("MyCacheControl");
Logger.debug("okhttp MyCacheControl ", cacheControl + " ");
okhttp3.Response originalResponse = chain.proceed(request);

return originalResponse.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", cacheControl)
.build();
}
}


it is working fine but i want to know the best way to achieve what i want.also is there another way to identify my requests and differentiate between them other than Headers.

Answer Source

Finally,and thanks to andre tietz he came up with another solution through custom annoutations on the request.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download