緩存問題:
當(dāng)我們需要實(shí)現(xiàn)網(wǎng)絡(luò)請(qǐng)求緩存時(shí),okhhttp已經(jīng)幫我們實(shí)現(xiàn)好了,只需要在攔截器里面調(diào)用okhttp對(duì)應(yīng)的方法設(shè)置一下
@Override
public Response intercept(Chain chain) throws IOException {
Response originResponse = chain.proceed(chain.request());
//設(shè)置緩存時(shí)間為60秒,并移除了pragma消息頭,移除它的原因是因?yàn)閜ragma也是控制緩存的一個(gè)消息頭屬性
return originResponse.newBuilder().removeHeader("pragma")
.header("Cache-Control","max-age=60").build();
}
但是這樣做有一個(gè)前提: 對(duì)于同一個(gè)網(wǎng)絡(luò)請(qǐng)求,在不同是時(shí)間請(qǐng)求,url是不變的
1.對(duì)于后端, 有時(shí)候我們會(huì)在Head里面添加隨機(jī)的可變的參數(shù)(例如:時(shí)間戳MD5加密)
2.這樣即使是同一個(gè)網(wǎng)絡(luò)請(qǐng)求,不同的時(shí)間訪問,也會(huì)有不一樣的參數(shù),這樣就需要我們自己簡(jiǎn)單實(shí)現(xiàn)緩存策略
緩存策略:
只要服務(wù)器返回的JSON不一樣,及替換緩存文件
public class HttpInterceptor implements Interceptor {
private final String TAG = HttpInterceptor.class.getSimpleName();
// log日志
private final StringBuilder logBuilder = new StringBuilder();
/**********************************************************************************************/
public HttpInterceptor() {
}
/**********************************************************************************************/
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder requestBuilder = request.newBuilder();
// 請(qǐng)求URL
final String url = request.url().toString();
// 下載文件
boolean isDownload = ("1".equals(request.header("xDownload")));
// 下載請(qǐng)求
if (isDownload) {
LogUtil.e(TAG, "intercept[下載apk] ==> url = " + url);
Response proceed = chain.proceed(requestBuilder.build());
return proceed
.newBuilder()
.body(proceed.body())
.build();
}
// 普通請(qǐng)求
else {
// 是否需要緩存
boolean needCache = ("1".equals(request.header("xCached")));
// 是否需要登錄
boolean needLogin = ("1".equals(request.header("xLogin")));
// 自定義User-Agent
requestBuilder.addHeader("User-Agent", "111");
requestBuilder.addHeader("Cache-Control", "no-cache");
// 開發(fā)環(huán)境
if (BuildConfig.DEBUG) {
logBuilder.delete(0, logBuilder.length());
logBuilder.append("====> Http " + request.method() + " url = ")
.append(url)
.append('\n');
logBuilder.append("====> Http header: xCached = ").append(needCache)
.append(", xLogin = ").append(needLogin)
.append('\n');
// POST請(qǐng)求
if ("POST".equalsIgnoreCase(request.method())) {
RequestBody requestBody = request.body();
if (requestBody instanceof FormBody) {
FormBody formBody = (FormBody) requestBody;
int size = formBody.size();
Map<String, String> map = new HashMap<>(size);
for (int i = 0; i < size; i++) {
map.put(formBody.name(i), formBody.value(i));
}
if (BuildConfig.DEBUG) {
logBuilder.append("====> Http Post Parameters = ")
.append(new GsonBuilder().setPrettyPrinting().create().toJson(map))
.append('\n');
}
}
}
}
// 需要登錄
if (needLogin) {
String userId = "111";
String token = "222";
if (!TextUtils.isEmpty(userId) && !TextUtils.isEmpty(token)) {
String nonce = DeviceUtil.getRandomString(16);
long timestamp = System.currentTimeMillis();
String sign = EncryptUtil.md5(userId + token + nonce + timestamp);
// 添加公共參數(shù)
HttpUrl httpUrl = request.url().newBuilder()
.addQueryParameter("userId", userId)
.addQueryParameter("nonce", nonce)
.addQueryParameter("timestamp", String.valueOf(timestamp))
.addQueryParameter("sign", sign)
.build();
Map<String, Object> map = new HashMap<>();
map.put("userId", userId);
map.put("nonce", nonce);
map.put("timestamp", timestamp + "");
map.put("sign", sign);
if (BuildConfig.DEBUG) {
logBuilder.append("====> Http Auth Parameters = ")
.append(new GsonBuilder().setPrettyPrinting().create().toJson(map))
.append('\n');
}
requestBuilder.url(httpUrl);
}
}
Response response;
try {
response = chain.proceed(requestBuilder.build());
if (needCache) {
LogUtil.e(TAG, "====> Net[網(wǎng)絡(luò)正常, 需要緩存]");
ResponseBody responseBody = response.body();
String body = responseBody.string();
if (response.isSuccessful()) {
HttpResult httpResult = new Gson().fromJson(body, HttpResult.class);
// 請(qǐng)求成功,data不為null,寫緩存
if (httpResult.getStatus() == 0 && !body.contains("\"data\":null")) {
// 1. 讀取最近保存的緩存
List<HttpJson> list = DBManager.getHttpJsonDao().queryBuilder().where(HttpJsonDao.Properties.Url.eq(url)).list();
if (null != list && list.size() > 0) {
HttpJson cache = list.get(0);
if (null != cache && !cache.getJson().equals(body)) {
LogUtil.e(TAG, "====> Net[網(wǎng)絡(luò)正常, DATA存在, 緩存存在, JSON更新]");
cache.setJson(body);
DBManager.getHttpJsonDao().update(cache);
} else {
LogUtil.e(TAG, "====> Net[網(wǎng)絡(luò)正常, DATA存在, 緩存存在, JSON不變]");
}
} else {
LogUtil.e(TAG, "====> Net[網(wǎng)絡(luò)正常, DATA存在, 緩存為空, JSON保存]");
HttpJson model = new HttpJson();
model.setUrl(url);
model.setJson(body);
DBManager.getHttpJsonDao().insert(model);
}
if (BuildConfig.DEBUG) {
logBuilder.append("====> Http response[web] = ").append(body);
}
} else {
LogUtil.e(TAG, "====> Net[網(wǎng)絡(luò)正常, DATA為空]");
// 請(qǐng)求成功,data為null,讀緩存,并重新構(gòu)建response
List<HttpJson> list = DBManager.getHttpJsonDao().queryBuilder().where(HttpJsonDao.Properties.Url.eq(url)).list();
if (null != list && list.size() > 0) {
HttpJson cache = list.get(0);
if (null != cache && !TextUtils.isEmpty(cache.getJson())) {
body = cache.getJson();
if (BuildConfig.DEBUG) {
logBuilder.append("====> Http response[cache] = ").append(body);
}
}
}
}
} else {
// 請(qǐng)求失敗,讀緩存,并重新構(gòu)建response
List<HttpJson> list = DBManager.getHttpJsonDao().queryBuilder().where(HttpJsonDao.Properties.Url.eq(url)).list();
if (null != list && list.size() > 0) {
HttpJson cache = list.get(0);
if (null != cache && !TextUtils.isEmpty(cache.getJson())) {
body = cache.getJson();
if (BuildConfig.DEBUG) {
logBuilder.append("====> Http response[cache] = ").append(body);
}
}
}
}
return response.newBuilder().body(ResponseBody.create(responseBody.contentType(), body)).build();
} else {
LogUtil.e(TAG, "====> Net[網(wǎng)絡(luò)正常, 不要緩存]");
if (true) {
ResponseBody responseBody = response.body();
String body = responseBody.string();
if (BuildConfig.DEBUG) {
logBuilder.append("====> Http response[web] = ").append(body);
}
return response.newBuilder().body(ResponseBody.create(responseBody.contentType(), body)).build();
} else {
return response;
}
}
} catch (Exception e) {
LogUtil.e(TAG, e.getMessage(), e);
if (needCache) {
LogUtil.e(TAG, "====> Net[網(wǎng)絡(luò)異常, 需要緩存]");
// 請(qǐng)求失敗,讀緩存,并重新構(gòu)建response
List<HttpJson> list = DBManager.getHttpJsonDao().queryBuilder().where(HttpJsonDao.Properties.Url.eq(url)).list();
if (null != list && list.size() > 0) {
HttpJson cache = list.get(0);
if (null != cache) {
String json = cache.getJson();
if (!TextUtils.isEmpty(json)) {
LogUtil.e(TAG, "====> Net[網(wǎng)絡(luò)異常, 緩存存在, JSON存在]");
if (BuildConfig.DEBUG) {
logBuilder.append("====> Http response[cache] = ").append(json);
}
// 重新構(gòu)建 200 的請(qǐng)求
return new Response.Builder()
.code(200)
.message("OK, but from cache")
.protocol(Protocol.HTTP_1_1)
.request(request)
.body(ResponseBody.create(MediaType.parse("application/json"), json))
.build();
} else {
LogUtil.e(TAG, "====> Net[網(wǎng)絡(luò)異常, 緩存存在, JSON為空]");
}
} else {
LogUtil.e(TAG, "====> Net[網(wǎng)絡(luò)異常, 緩存為空]");
}
} else {
LogUtil.e(TAG, "====> Net[網(wǎng)絡(luò)異常, 緩存為空]");
}
} else {
LogUtil.e(TAG, "====> Net[網(wǎng)絡(luò)異常, 不要緩存]");
}
throw e;
} finally {
LogUtil.e(TAG, logBuilder.toString());
}
}
}
}