Glide图片加载框架的强大,使用简单相信是众所周知的,之前在项目中一直都用的,但是最近在项目中需要使用代理,在加载图片的时候也要用,本来以为很简单,网上查了下发现这一块其实没那么容易啊,只能边看源码边学习解决。
- Glide项目地址: Glide Github
- Glide WIKI
- Glide 4.0源码解析
查看源码,可以看到进行网络请求的时候,使用的是HttpUrlConnection(这里我们没有使用OKHttp或者Volley进行优化,有兴趣的可以查看WIKI文档进行集成)
源码分析基于Glide 4.1.1
Glide常用方式与源码分析:
Glide.with(activity).load(url).into(imageview)
1. 初始化,配置 Loader
- 查看Glide类,Registry类:
Glide.with(activity),对Glide进行初始化,主要方法如下:
Glide.getRetriever()
Glide.get(context)
Glide.checkAndInitializeGlide(context);
Glide.initializeGlide
Glide glide = builder.build(applicationContext);
Glide 用GlideBuilder对象生成Glide对象,Glide类的构造函数中,对Glide对象进行初始化,这里涉及到的初始化的重点是对Registry对象的初始化:
registry.register(ByteBuffer.class, new ByteBufferEncoder())
.register(InputStream.class, new StreamEncoder(arrayPool))
/* Bitmaps */
.append(ByteBuffer.class, Bitmap.class,
new ByteBufferBitmapDecoder(downsampler))
.append(InputStream.class, Bitmap.class,
new StreamBitmapDecoder(downsampler, arrayPool))
.append(ParcelFileDescriptor.class, Bitmap.class, new VideoBitmapDecoder(bitmapPool))
.register(Bitmap.class, new BitmapEncoder())
/* GlideBitmapDrawables */
.append(ByteBuffer.class, BitmapDrawable.class,
new BitmapDrawableDecoder<>(resources, bitmapPool,
new ByteBufferBitmapDecoder(downsampler)))
.append(InputStream.class, BitmapDrawable.class,
new BitmapDrawableDecoder<>(resources, bitmapPool,
new StreamBitmapDecoder(downsampler, arrayPool)))
.append(ParcelFileDescriptor.class, BitmapDrawable.class,
new BitmapDrawableDecoder<>(resources, bitmapPool, new VideoBitmapDecoder(bitmapPool)))
.register(BitmapDrawable.class, new BitmapDrawableEncoder(bitmapPool, new BitmapEncoder()))
/* GIFs */
.prepend(InputStream.class, GifDrawable.class,
new StreamGifDecoder(registry.getImageHeaderParsers(), byteBufferGifDecoder, arrayPool))
.prepend(ByteBuffer.class, GifDrawable.class, byteBufferGifDecoder)
.register(GifDrawable.class, new GifDrawableEncoder())
/* GIF Frames */
.append(GifDecoder.class, GifDecoder.class, new UnitModelLoader.Factory())
.append(GifDecoder.class, Bitmap.class, new GifFrameResourceDecoder(bitmapPool))
/* Files */
.register(new ByteBufferRewinder.Factory())
.append(File.class, ByteBuffer.class, new ByteBufferFileLoader.Factory())
.append(File.class, InputStream.class, new FileLoader.StreamFactory())
.append(File.class, File.class, new FileDecoder())
.append(File.class, ParcelFileDescriptor.class, new FileLoader.FileDescriptorFactory())
.append(File.class, File.class, new UnitModelLoader.Factory())
/* Models */
.register(new InputStreamRewinder.Factory(arrayPool))
.append(int.class, InputStream.class, new ResourceLoader.StreamFactory(resources))
.append(
int.class,
ParcelFileDescriptor.class,
new ResourceLoader.FileDescriptorFactory(resources))
.append(Integer.class, InputStream.class, new ResourceLoader.StreamFactory(resources))
.append(
Integer.class,
ParcelFileDescriptor.class,
new ResourceLoader.FileDescriptorFactory(resources))
.append(String.class, InputStream.class, new DataUrlLoader.StreamFactory())
.append(String.class, InputStream.class, new StringLoader.StreamFactory())
.append(String.class, ParcelFileDescriptor.class, new StringLoader.FileDescriptorFactory())
.append(Uri.class, InputStream.class, new HttpUriLoader.Factory())
.append(Uri.class, InputStream.class, new AssetUriLoader.StreamFactory(context.getAssets()))
.append(
Uri.class,
ParcelFileDescriptor.class,
new AssetUriLoader.FileDescriptorFactory(context.getAssets()))
.append(Uri.class, InputStream.class, new MediaStoreImageThumbLoader.Factory(context))
.append(Uri.class, InputStream.class, new MediaStoreVideoThumbLoader.Factory(context))
.append(
Uri.class,
InputStream.class,
new UriLoader.StreamFactory(context.getContentResolver()))
.append(Uri.class, ParcelFileDescriptor.class,
new UriLoader.FileDescriptorFactory(context.getContentResolver()))
.append(Uri.class, InputStream.class, new UrlUriLoader.StreamFactory())
.append(URL.class, InputStream.class, new UrlLoader.StreamFactory())
.append(Uri.class, File.class, new MediaStoreFileLoader.Factory(context))
.append(GlideUrl.class, InputStream.class, new HttpGlideUrlLoader.Factory())
.append(byte[].class, ByteBuffer.class, new ByteArrayLoader.ByteBufferFactory())
.append(byte[].class, InputStream.class, new ByteArrayLoader.StreamFactory())
/* Transcoders */
.register(Bitmap.class, BitmapDrawable.class,
new BitmapDrawableTranscoder(resources, bitmapPool))
.register(Bitmap.class, byte[].class, new BitmapBytesTranscoder())
.register(GifDrawable.class, byte[].class, new GifDrawableBytesTranscoder());
- Registry类是用来:
/**
* Manages component registration to extend or replace Glide's default loading, decoding, and
* encoding logic.
*/
简单来说:就是根据传入什么样的modelClass来取使用哪个ModelLoaderFactory。类似于EventBus 这种,根据传入的类型调用具体的处理逻辑。这里我们的httpUrl字符串在Glide中会被封装成GlideUrl对象,对应的loader类是HttpGlideUrlLoader
GlideUrl.class, InputStream.class, new HttpGlideUrlLoader.Factory()
2. GlideApp
在Glide4中会在make之后自动生成GlideApp:
- 在build.gradle中添加:
dependencies {
compile 'com.github.bumptech.glide:glide:4.1.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.1.1'
}
其中第二句annotationProcessor 是重点
- 使用:@GlideModule
@GlideModule
public class MyGlideAppModule extends AppGlideModule {
@Override
public void applyOptions(Context context, GlideBuilder builder) {
super.applyOptions(context, builder);
int memoryCacheSizeBytes = 1024 * 1024 * 20; // 20mb
builder.setMemoryCache(new LruResourceCache(memoryCacheSizeBytes));
}
@Override
public boolean isManifestParsingEnabled() {
return false;
}
}
- Clean and make
3. HttpGlideUrlLoader,HttpUrlFetcher
这两个类主要负责进行网络请求。
- HttpUrlFetcher 这个类中使用HttpURLConnection进行网络请求
@Override
public void loadData(Priority priority, DataCallback super InputStream> callback) {
long startTime = LogTime.getLogTime();
final InputStream result;
try {
result = loadDataWithRedirects(glideUrl.toURL(), 0 /*redirects*/, null /*lastUrl*/,
glideUrl.getHeaders());
} catch (IOException e) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Failed to load data for url", e);
}
callback.onLoadFailed(e);
return;
}
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Finished http url fetcher fetch in " + LogTime.getElapsedMillis(startTime)
+ " ms and loaded " + result);
}
callback.onDataReady(result);
}
private InputStream loadDataWithRedirects(URL url, int redirects, URL lastUrl,
Map headers) throws IOException {
if (redirects >= MAXIMUM_REDIRECTS) {
throw new HttpException("Too many (> " + MAXIMUM_REDIRECTS + ") redirects!");
} else {
// Comparing the URLs using .equals performs additional network I/O and is generally broken.
// See http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html.
try {
if (lastUrl != null && url.toURI().equals(lastUrl.toURI())) {
throw new HttpException("In re-direct loop");
}
} catch (URISyntaxException e) {
// Do nothing, this is best effort.
}
}
urlConnection = connectionFactory.build(url);
for (Map.Entry headerEntry : headers.entrySet()) {
urlConnection.addRequestProperty(headerEntry.getKey(), headerEntry.getValue());
}
urlConnection.setConnectTimeout(timeout);
urlConnection.setReadTimeout(timeout);
urlConnection.setUseCaches(false);
urlConnection.setDoInput(true);
// Stop the urlConnection instance of HttpUrlConnection from following redirects so that
// redirects will be handled by recursive calls to this method, loadDataWithRedirects.
urlConnection.setInstanceFollowRedirects(false);
// Connect explicitly to avoid errors in decoders if connection fails.
urlConnection.connect();
if (isCancelled) {
return null;
}
final int statusCode = urlConnection.getResponseCode();
if (statusCode / 100 == 2) {
return getStreamForSuccessfulRequest(urlConnection);
} else if (statusCode / 100 == 3) {
String redirectUrlString = urlConnection.getHeaderField("Location");
if (TextUtils.isEmpty(redirectUrlString)) {
throw new HttpException("Received empty or null redirect url");
}
URL redirectUrl = new URL(url, redirectUrlString);
return loadDataWithRedirects(redirectUrl, redirects + 1, url, headers);
} else if (statusCode == -1) {
throw new HttpException(statusCode);
} else {
throw new HttpException(urlConnection.getResponseMessage(), statusCode);
}
}
而HttpUrlConnection 是使用HttpUrlFetcher中的connectionFactory字段进行生成的HttpUrlConnection:
@Override
public HttpURLConnection build(URL url) throws IOException {
return (HttpURLConnection) url.openConnection();
}
- HttpGlideUrlLoader:核心代码如下,创建HttpUrlFetcher进行网络请求
@Override
public LoadData buildLoadData(GlideUrl model, int width, int height,
Options options) {
// GlideUrls memoize parsed URLs so caching them saves a few object instantiations and time
// spent parsing urls.
GlideUrl url = model;
if (modelCache != null) {
url = modelCache.get(model, 0, 0);
if (url == null) {
modelCache.put(model, 0, 0, model);
url = model;
}
}
int timeout = options.get(TIMEOUT);
return new LoadData<>(url, new HttpUrlFetcher(url, timeout));
}
主要的代码分析就到这里。
不难看出要想支持Proxy只需要改动一行代码即可:
@Override
public HttpURLConnection build(URL url) throws IOException {
return (HttpURLConnection) url.openConnection(proxy);
}
当然还要加一些是否存在proxy的判断:
@Override
public HttpURLConnection build(URL url) throws IOException {
HttpURLConnection conn = null;
if (existProxy()) {
conn = (HttpURLConnection) url.openConnection(getProxy());
} else {
conn = (HttpURLConnection) url.openConnection();
}
}
- 如果需要添加用户名和密码认证:
if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(pwd)) {
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication(username,
pwd.toCharArray()));
}
};
Authenticator.setDefault(authenticator);
} else {
Authenticator.setDefault(null);
}
注意 关键是如何添加???
这里能够想到的是使用自定义的HttpGlideUrlLoader。
问题1. HttpUrlFetcher中的connectionFactory是final的,HttpUrlConnectionFactory 是default的不能扩展,HttpUrlFetchery构造函数也是default的
// Visible for testing.
HttpUrlFetcher(GlideUrl glideUrl, int timeout, HttpUrlConnectionFactory connectionFactory) {
this.glideUrl = glideUrl;
this.timeout = timeout;
this.connectionFactory = connectionFactory;
}
解决方案
1. 方案一
修改Glide源码,重新打包。或者直接将源码放到项目中修改
- HttpUrlFetcher第二个构造方法置为public,将HttpUrlFetcher$HttpUrlConnectionFactory 接口置为 public
- HttpGlideUrlLoader中添加Proxy字段与设置方法,建议是 static,如果proxy为空就调用HttpUrlFetcher第一个构造函数,如果不为空就调用第二个,实现HttpUrlFetcher$HttpUrlConnectionFactory接口并将proxy传入即可
private static class ProxyHttpUrlConnectionFactory implements HttpUrlConnectionFactory {
private Proxy mProxy
private static boolean setProxy(proxy p,String username,String pwd){
mProxy = p;
if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(pwd)) {
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication(username,
pwd.toCharArray()));
}
};
Authenticator.setDefault(authenticator);
} else {
Authenticator.setDefault(null);
}
}
private static boolean exist(){
return mProxy != null;
}
@Synthetic
public ProxyHttpUrlConnectionFactory () { }
@Override
public HttpURLConnection build(URL url) throws IOException {
//return (HttpURLConnection) url.openConnection(mProxy);
}
}
这个方案有点:
- 改动少
- 容易理解和实现
缺点:
- 改动了源码,对于后续Glide升级存在问题
2. 方案二
自定义HttpGlideUrlLoader,前面说到的Registry类的初始化中,当modelClass是GlideUrl时,使用的就是HttpGlideUrlLoader,那这里取代这个默认的Loader,使用自定义即可:
假设自定义的是MyHttpGlideUriLoader, 扩展 extends ModelLoader
registry.replace(GlideUrl.class, InputStream.class, new MyHttpGlideUrlLoader.Factory());
并把HttpGlideUrlLoader中的代码复制到MyHttpGlideUriLoader,区别只有buildLoadData方法中最后return时。
然后自定义MyHttpUrlFetcher,将HttpUrlFetcher复制一份,区别只有DefaultHttpUrlConnectionFactory :
private static class DefaultHttpUrlConnectionFactory implements HttpUrlConnectionFactory {
private static Proxy mProxy
private static boolean setProxy(proxy p,String username,String pwd){
mProxy = p;
if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(pwd)) {
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication(username,
pwd.toCharArray()));
}
};
Authenticator.setDefault(authenticator);
} else {
Authenticator.setDefault(null);
}
}
private static boolean exist(){
return mProxy != null;
}
@Synthetic
DefaultHttpUrlConnectionFactory() { }
@Override
public HttpURLConnection build(URL url) throws IOException {
//return (HttpURLConnection) url.openConnection();
// 改成
HttpURLConnection conn = null;
if (existProxy()) {
conn = (HttpURLConnection) url.openConnection(mProxy);
} else {
conn = (HttpURLConnection) url.openConnection();
}
}
}
这个方案其实很好理解的。但是这个方案需要改的东西太多,有点挫,其实真正的改动只是HttpUrlConnectionFactory.build 方法而已,
优点:
- 容易理解
缺点:
- 改动太多,添加太多冗余代码
3. 方案三
使用反射+动态代理
思路说明:因为真正需要修改的只是HttpUrlFetcher$HttpUrlConnectionFactory 接口实现的build方法,如果能够将HttpUrlFetcher.connectionFactory替换掉就行了,所以这里需要使用到反射。先反射出HttpUrlConnectionFactory接口,并实现,然后反射HttpUrlFetcher.connectionFactory字段并赋值。这就是整体的思路
反射这里就不讲了,主要是如何实现HttpUrlConnectionFactory接口呢?
动态代理,如果看过retrofit源码的话应该不难理解。
首先跟方案二一样,自定义MyGlideUrlLoader,使用register.replace替换默认的loader。
在MyGlideUrlLoader中buildLoadData方法进行复写:
public class MyHttpGlideUrlLoader extends HttpGlideUrlLoader {
private static final String TAG = MyHttpGlideUrlLoader.class.getSimpleName();
public MyHttpGlideUrlLoader(ModelCache modelCache) {
super(modelCache);
}
@Override
public LoadData buildLoadData(GlideUrl model, int width, int height, Options options) {
LoadData old = super.buildLoadData(model, width, height, options);//if proy is not null,drop the result,just set the modelCache
if (!MyHttpUrlConnectionFactory.existProxy()) {
return old;
}
//反射出HttpUrlFetcher$HttpUrlConnectionFactory接口
Class factoryInterface = null;
try {
factoryInterface = Class.forName("com.bumptech.glide.load.data.HttpUrlFetcher$HttpUrlConnectionFactory");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//动态代理这个接口
Object factoryProxy = null;
if (factoryInterface != null) {
factoryProxy = java.lang.reflect.Proxy.newProxyInstance(factoryInterface.getClassLoader(),
new Class[]{factoryInterface},
new MyInvocationHandler(new MyHttpUrlConnectionFactory()));
}
if (old != null && old.fetcher != null && factoryProxy != null) {
try {
//给connectionFactory字段赋新的值
Field factoryField = HttpUrlFetcher.class.getDeclaredField("connectionFactory");
factoryField.setAccessible(true);
factoryField.set(old.fetcher, factoryProxy);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return old;
}
private static class MyInvocationHandler implements InvocationHandler {
private MyHttpUrlConnectionFactory factory;
public MyInvocationHandler(MyHttpUrlConnectionFactory f) {
factory = f;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
URL url = null;
if(args != null && args.length > 0 && args[0] instanceof URL){
url = (URL) args[0];
}
if(url != null){
return factory.build(url);
}
return method.invoke(proxy,args);
}
}
//代理类中真正的执行是这个类
public static class MyHttpUrlConnectionFactory {
private static Proxy sProxyConfig;
public static void setProxy(Proxy proxy,final String username,final String pwd) {
if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(pwd)) {
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication(username,
pwd.toCharArray()));
}
};
Authenticator.setDefault(authenticator);
} else {
Authenticator.setDefault(null);
}
MyHttpUrlConnectionFactory.sProxyConfig = proxy;
}
public static void clearProxy() {
setProxy(null,null,null);
}
public static boolean existProxy() {
return sProxyConfig != null;
}
public MyHttpUrlConnectionFactory() {
}
public HttpURLConnection build(URL url) throws IOException {
HttpURLConnection conn = null;
if (existProxy()) {
conn = (HttpURLConnection) url.openConnection(sProxyConfig);
} else {
conn = (HttpURLConnection) url.openConnection();
}
return conn;
}
}
/**
* The default factory for {@link MyHttpGlideUrlLoader}s.
*/
public static class Factory implements ModelLoaderFactory {
private final ModelCache modelCache = new ModelCache<>(500);
@Override
public ModelLoader build(MultiModelLoaderFactory multiFactory) {
return new MyHttpGlideUrlLoader(modelCache);
}
@Override
public void teardown() {
// Do nothing.
}
}
}
方案三优点:
- 代码改动量不大
- 使用反射和动态代理,比方案二看上去高大上了点,动态代理之前只是看没有实践过,呵呵。。。。
缺点:
- 需要理解反射和动态代理
- 在Glide后续版本升级中,如果com.bumptech.glide.load.data.HttpUrlFetcher$HttpUrlConnectionFactory名称改了,或者com.bumptech.glide.load.data.HttpUrlFetcher.connectionFactory字段名称改了,就歇菜了。。。
综上
个人还是倾向于方案一,改动量很小,但是在项目中要求不能改动第三方代码,所以使用了方案三