Last active
December 12, 2016 14:52
-
-
Save reixa00/94543264bbe3b9d94d26 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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