缓存问题:
当我们需要实现网络请求缓存时,okhhttp已经帮我们实现好了,只需要在拦截器里面调用okhttp对应的方法设置一下
@Override
public Response intercept(Chain chain) throws IOException {
Response originResponse = chain.proceed(chain.request());
//设置缓存时间为60秒,并移除了pragma消息头,移除它的原因是因为pragma也是控制缓存的一个消息头属性
return originResponse.newBuilder().removeHeader("pragma")
.header("Cache-Control","max-age=60").build();
}
但是这样做有一个前提: 对于同一个网络请求,在不同是时间请求,url是不变的
1.对于后端, 有时候我们会在Head里面添加随机的可变的参数(例如:时间戳MD5加密)
2.这样即使是同一个网络请求,不同的时间访问,也会有不一样的参数,这样就需要我们自己简单实现缓存策略
缓存策略:
只要服务器返回的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();
// 请求URL
final String url = request.url().toString();
// 下载文件
boolean isDownload = ("1".equals(request.header("xDownload")));
// 下载请求
if (isDownload) {
LogUtil.e(TAG, "intercept[下载apk] ==> url = " + url);
Response proceed = chain.proceed(requestBuilder.build());
return proceed
.newBuilder()
.body(proceed.body())
.build();
}
// 普通请求
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");
// 开发环境
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请求
if ("POST".equalsIgnoreCase(request.method())) {
RequestBody requestBody = request.body();
if (requestBody instanceof FormBody) {
FormBody formBody = (FormBody) requestBody;
int size = formBody.size();
Map 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);
// 添加公共参数
HttpUrl httpUrl = request.url().newBuilder()
.addQueryParameter("userId", userId)
.addQueryParameter("nonce", nonce)
.addQueryParameter("timestamp", String.valueOf(timestamp))
.addQueryParameter("sign", sign)
.build();
Map 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[网络正常, 需要缓存]");
ResponseBody responseBody = response.body();
String body = responseBody.string();
if (response.isSuccessful()) {
HttpResult httpResult = new Gson().fromJson(body, HttpResult.class);
// 请求成功,data不为null,写缓存
if (httpResult.getStatus() == 0 && !body.contains("\"data\":null")) {
// 1. 读取最近保存的缓存
List 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[网络正常, DATA存在, 缓存存在, JSON更新]");
cache.setJson(body);
DBManager.getHttpJsonDao().update(cache);
} else {
LogUtil.e(TAG, "====> Net[网络正常, DATA存在, 缓存存在, JSON不变]");
}
} else {
LogUtil.e(TAG, "====> Net[网络正常, 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[网络正常, DATA为空]");
// 请求成功,data为null,读缓存,并重新构建response
List 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 {
// 请求失败,读缓存,并重新构建response
List 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[网络正常, 不要缓存]");
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[网络异常, 需要缓存]");
// 请求失败,读缓存,并重新构建response
List 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[网络异常, 缓存存在, JSON存在]");
if (BuildConfig.DEBUG) {
logBuilder.append("====> Http response[cache] = ").append(json);
}
// 重新构建 200 的请求
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[网络异常, 缓存存在, JSON为空]");
}
} else {
LogUtil.e(TAG, "====> Net[网络异常, 缓存为空]");
}
} else {
LogUtil.e(TAG, "====> Net[网络异常, 缓存为空]");
}
} else {
LogUtil.e(TAG, "====> Net[网络异常, 不要缓存]");
}
throw e;
} finally {
LogUtil.e(TAG, logBuilder.toString());
}
}
}
}