在我的应用图片中,内容经常变化(比如一周一次),并且图像保持不变。我正在使用毕加索进行图像加载。我的问题是我可以将年龄设置为缓存条目并使用“if-modified-since”和“ETag”之类的标题吗?
答案 0 :(得分:2)
这就是我解决它的方法。
Interceptor interceptor = new Interceptor() {
public static final String TAG = "RequestInterceptor";
@Override
public Response intercept(Chain chain) throws IOException {
final Request original = chain.request(); //Original request initiated
final Response response; //Response for given url
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder().header("if-modified-since", last-modified-date-for-image).method(original.method(), original.body());
Request request = requestBuilder.build();
response = chain.proceed(request);
Log.d(TAG, "Intercepting status code : " + response.code());
Log.d(TAG, "Intercepting requests : Url :" + request.url().toString());
Log.d(TAG, "Intercepting requests : if-modified-since : " + response.header("if-modified-since".toLowerCase()));
/* if response code is 200 means we have updated image otherwise return older one.*/
if (response.code() == 200) {
return response;
} else {
return chain.proceed(original);
}
}
};
//Create OkHttpClient for picasso downloader and add request interceptor.
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(interceptor).build();
//Instantiate okHttp3Downloader with okHttpClient
OkHttp3Downloader okHttpDownloader = new OkHttp3Downloader(okHttpClient);
//Create picasso instance
picasso = new Picasso.Builder(this).downloader(okHttpDownloader).build();
//load image in imageview 'img'
picasso.load("image url").into(img);
您可以使用' ETag'而不是' if-modified-since'。
已知问题:设备离线时未加载图片。请强行从缓存加载。