同一应用混用Glide、Retrofit与OkHttp 4.x引发编译版本冲突问题
问题解答
问题1:升级OkHttp到4.10.0后,OkHttpClient不被识别为Call.Factory类型
原因
Glide 4.14.2的okhttp3-integration模块是为OkHttp 3.x开发适配的,而OkHttp 4.x是用Kotlin完全重构的版本。尽管API层面保持了兼容,但字节码层面Call.Factory的类型匹配逻辑出现了差异——Glide集成库预期的是OkHttp 3.x的Call.Factory实现,而OkHttp 4.x的OkHttpClient虽然实现了同名接口,但类的字节码标识不同,导致编译时类型不匹配。
解决方案
有三种可行方案:
- 方案一:升级Glide到兼容OkHttp4的版本
将Glide及对应集成库升级到4.15.0或更高版本,这些版本的okhttp3-integration已经适配了OkHttp4:implementation 'com.github.bumptech.glide:glide:4.15.0' implementation 'com.github.bumptech.glide:okhttp3-integration:4.15.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.15.0' - 方案二:显式类型转换(不升级Glide)
在代码中强制将OkHttpClient转型为Call.Factory,绕过编译时的类型检查:@GlideModule public class CustomGlideModule extends AppGlideModule { @Override public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) { OkHttpClient client = new OkHttpClient.Builder().dns(new MyDns()).build(); // 显式转型为Call.Factory OkHttpUrlLoader.Factory factory = new OkHttpUrlLoader.Factory((okhttp3.Call.Factory) client); registry.replace(GlideUrl.class, InputStream.class, factory); } } - 方案三:降级回OkHttp3.x版本
如果暂时不需要OkHttp4的特性,可以回退到OkHttp3.x版本,避免兼容性问题。
问题2:如何选择OkHttp的版本?
核心原则
选择所有依赖链中最高的兼容版本,Gradle在处理依赖冲突时会默认选择最高版本,但手动声明最高兼容版本可以避免潜在的依赖不一致问题。
具体选择
- 优先选择OkHttp 3.14.9:
- Retrofit 2.9.0依赖的OkHttp版本是3.14.9,这个版本高于Glide 4.14.2依赖的3.10.0
- OkHttp 3.x版本向后兼容,3.14.9可以完全适配Glide 4.14.2的
okhttp3-integration模块,同时满足Retrofit和你直接调用OkHttp的需求
- 如果要升级到OkHttp4.x:
- 必须同步升级Glide到4.15.0+(确保集成库适配OkHttp4),同时Retrofit 2.9.0本身支持OkHttp4,无需升级Retrofit
最终推荐的依赖配置(使用OkHttp 3.14.9)
implementation 'com.squareup.okhttp3:okhttp:3.14.9' implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.14.9' implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' implementation 'com.github.bumptech.glide:glide:4.14.2' implementation 'com.github.bumptech.glide:okhttp3-integration:4.14.2' annotationProcessor 'com.github.bumptech.glide:compiler:4.14.2'
内容的提问来源于stack exchange,提问作者Martin Frank
相关产品推荐
相关产品推荐

