Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odemolliens/a948bafbaf06bbf8c72f993cdfb1395d to your computer and use it in GitHub Desktop.
Save odemolliens/a948bafbaf06bbf8c72f993cdfb1395d to your computer and use it in GitHub Desktop.
Shared OkHttp application Interceptor that will add or intercept E-Tag hash for ALL requests on client instance
// by Nikola Despotoski
import android.content.Context;
import android.text.TextUtils;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
/**
* Created by nikola on 1/27/15.
*/
public class OkHttpSharedEtagNetworkInterceptor implements Interceptor{
private static final java.lang.String IF_NONE_MATCH = "If-None-Match";
private static final java.lang.String ETAG = "ETag";
private final Context mContext;
public OkHttpSharedEtagNetworkInterceptor(Context context){
mContext = context;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
//----rebuild request from scratch---
Request.Builder newRequest = request.newBuilder();
newRequest.cacheControl(request.cacheControl());
newRequest.url(request.url());
if(request.method().equals("GET"))
newRequest.get();
else
newRequest.method(request.method(), request.body());
//----retrieve last stored hash
String etag = getEtag();
Headers headers = request.headers();
Headers.Builder newHeaders = headers.newBuilder();
//---if exists add it to headers---
if(!TextUtils.isEmpty(etag)){
newHeaders.add(IF_NONE_MATCH, etag);
}
for(int i = 0; i < headers.size(); i++){
newHeaders.add(headers.name(i), headers.value(i));
}
headers = newHeaders.build();
newRequest.headers(headers);
request = newRequest.build();
Response response = chain.proceed(request);
//---- if received Not modified 304 code, store it to preferences for later ----
if(response.code() == 304){
storeEtag(response.header(ETAG));
}
return response;
}
private void storeEtag(String header) {
SharedPreferencesUtil.writeString(mContext, ETAG, header);
}
public String getEtag() {
return SharedPreferencesUtil.getString(mContext, ETAG);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment