Glide加载带token图片,token每次都不一样,以自定义GlideUrl,以token前面的url作为key值。
但是adb开启了glide的log,发现不管token怎么变,glide都是加载第一次那个token的url,服务器收到的也是旧的url,导致图片过期后加载不出来。
而在Glide的listener回调打印log,却是最新的tokenUrl。
调用glide清空缓存的方法也无效。
加载图片的方法代码
MyGlideUrl glideUrl = new MyGlideUrl(url).build());
Glide.with(context)
.load(glideUrl)
.listener(new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
MyGlideUrl myGlideUrl = (MyGlideUrl) model;
Log.e(TAG, "glide-error-url= " + myGlideUrl.mUrl
+ "\n e = " + e);
return false;
}
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
return false;
}
})
.placeholder(R.drawable.loading)
.error(R.drawable.load_failed)
.into(imageView);
自定义GlideUrl代码
public static class MyGlideUrl extends GlideUrl {
private String mUrl;
public MyGlideUrl(String url) {
super(url);
mUrl = url;
}
@Override
public String getCacheKey() {
return toStringUrl().replace(findTokenParam(), "");
}
private String findTokenParam() {
String tokenParam = "";
int tokenKeyIndex = mUrl.indexOf("?auth_key=") >= 0 ? mUrl.indexOf("?auth_key=") :
mUrl.indexOf("&auth_key=");
if (tokenKeyIndex != -1) {
int nextAndIndex = mUrl.indexOf("&", tokenKeyIndex + 1);
if (nextAndIndex != -1) {
tokenParam = mUrl.substring(tokenKeyIndex + 1, nextAndIndex + 1);
} else {
tokenParam = mUrl.substring(tokenKeyIndex);
}
}
return tokenParam;
}
}
adb开启glide的log:
class com.bumptech.glide.load.engine.GlideException: Failed to load resource
There was 1 cause:
java.io.FileNotFoundException(http://xxx/icon?auth_key=1563264202)
glide监听回调的log:
glide-error-url= http://xxx/icon?auth_key=1563266341
e = com.bumptech.glide.load.engine.GlideException: Failed to load resource