第2章 Gradle依赖配置:Retrofit版本选择、Converter与Adapter依赖、OkHttp日志拦截器引入

2.1 Retrofit版本选择原则

Retrofit遵循语义化版本(SemVer),主版本号变更代表不兼容的API改动。当前稳定主系列为2.x(截至2025年)。选择版本时应关注:

  • 最新稳定版:优先使用Maven Central或GitHub Release标注的最新稳定版,避免使用测试版(alpha/beta/rc)。
  • Android API级别兼容性:Retrofit 2.x最低支持Android 4.0+(API 14),但当前应用通常已提升minSdk至21以上,无需额外顾虑。
  • 依赖传递兼容性:Retrofit核心库直接依赖OkHttp 3.x/4.x,选择Retrofit版本时需确保其声明的最低OkHttp版本与项目其余组件(如WebSocket、性能监控)兼容。
  • Release Notes检查:升级前阅读变更日志,重点关注Converter/Adapter适配器签名变化、Deprecated标记和移除的功能。
Retrofit版本最低OkHttp版本推荐用途维护状态
2.6.x3.12.x / 4.x旧项目稳定版本安全补丁
2.9.x4.9.x / 4.10+当前推荐版本活跃维护
2.10.x (如有)4.11+最新特性(KSP支持)预览/测试
建议在项目的 gradle.properties 中定义统一版本变量,便于跨模块升级时一次性调整。

2.2 Converter依赖与Adapter依赖

Converter负责将HTTP响应体(ResponseBody)反序列化为Java/Kotlin对象,以及将请求体序列化为RequestBody;Adapter负责将Call适配为特定异步类型(如RxJava Observable、Kotlin Coroutines Deferred)。

类型库Gradle坐标说明
ConverterGsoncom.squareup.retrofit2:converter-gson使用最广泛,基于反射
ConverterMoshicom.squareup.retrofit2:converter-moshi编译期代码生成,更轻量
ConverterKotlinx Serializationcom.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter纯Kotlin原生序列化
ConverterJacksoncom.squareup.retrofit2:converter-jackson适合已有Jackson生态的项目
AdapterRxJava3com.squareup.retrofit2:adapter-rxjava3返回 Observable/Single/Completable
AdapterKotlin Coroutinescom.squareup.retrofit2:retrofit2-kotlin-coroutines-adapter(或使用suspend函数原生)现在推荐直接使用suspend函数,该适配器已被取代
AdapterLiveDatacom.squareup.retrofit2:adapter-guava(或自定义)Android Architecture组件集成
如果项目使用Kotlin协程,Retrofit 2.6+ 已直接支持 suspend 函数,无需额外添加 Coroutines Adapter。添加时需注意版本冲突。

2.3 OkHttp日志拦截器引入

OkHttp的 HttpLoggingInterceptor 是调试阶段最实用的工具,可打印请求/响应的头信息、体内容、耗时等。生产环境下应当关闭或设置为仅打印头信息,避免敏感数据泄露和性能损耗。

添加依赖:

implementation("com.squareup.okhttp3:logging-interceptor:4.12.0")

在OkHttp Client中配置:

val loggingInterceptor = HttpLoggingInterceptor().apply {
    level = if (BuildConfig.DEBUG) {
        HttpLoggingInterceptor.Level.BODY
    } else {
        HttpLoggingInterceptor.Level.NONE
    }
}

val okHttpClient = OkHttpClient.Builder()
    .addInterceptor(loggingInterceptor)
    .build()
注意:使用 Level.BODY 会打印完整的请求体和响应体,调试完成后务必改为 Level.HEADERS 或 Level.NONE 再发布。

2.4 Gradle配置实战

以下为典型 Android 项目 build.gradle.kts(Kotlin DSL)依赖配置片段:

// 在项目级 gradle.properties 中定义版本变量
// retrofitVersion=2.9.0
// okhttpVersion=4.12.0

dependencies {
    // Retrofit 核心
    implementation("com.squareup.retrofit2:retrofit:${rootProject.ext["retrofitVersion"]}")

    // Converter - 选择一种
    implementation("com.squareup.retrofit2:converter-gson:${rootProject.ext["retrofitVersion"]}")
    // 或 implementation("com.squareup.retrofit2:converter-moshi:${rootProject.ext["retrofitVersion"]}")

    // Adapter - 如果需要 RxJava
    implementation("com.squareup.retrofit2:adapter-rxjava3:${rootProject.ext["retrofitVersion"]}")

    // OkHttp + 日志拦截器
    implementation("com.squareup.okhttp3:okhttp:${rootProject.ext["okhttpVersion"]}")
    implementation("com.squareup.okhttp3:logging-interceptor:${rootProject.ext["okhttpVersion"]}")
}
务必保证 Retrofit 声明的 OkHttp 版本与 logging-interceptor 版本一致;若存在其他依赖(如 Glide 或某个网络库)传递了不同版本的 OkHttp,需通过强制版本或 resolutionStrategy 统一。

2.5 常见错误与优化

  • 版本不一致导致 NoSuchMethodError:例如 Retrofit 2.9 依赖 OkHttp 4.9+,但项目中还存在 OkHttp 3.12 的传递依赖,运行时抛异常。使用 ./gradlew :app:dependencies 查看依赖树,用 constraints 或 force 统一版本。
  • 日志拦截器泄漏敏感数据:生产环境使用了 Level.BODY,导致 、密码等打印到 logcat。建议使用 BuildConfig.DEBUG 控制,或采用自定义拦截器过滤敏感字段。
  • Converter & Adapter 重复添加:同时引入了 Gson 和 Moshi 两个 Converter,或同时使用了 suspend 函数和 RxJava Adapter,会造成构建通过但运行时行为混乱。应只保留项目实际使用的组合。
  • 忽略 Kotlin 序列化步骤:若选择 Kotlinx Serialization Converter,还需在 Gradle 中添加 Kotlin 序列化插件和运行时库,且实体类需标注 @Serializable。
Gradle依赖配置结构图 Gradle依赖配置结构:Retrofit + OkHttp + 插件 Retrofit 核心库 com.squareup.retrofit2:retrofit:2.9.0 OkHttp 核心库 com.squareup.okhttp3:okhttp:4.12.0 依赖 Converter: Gson converter-gson Converter: Moshi converter-moshi Converter: Kotlinx kotlinx-serialization Adapter: RxJava3 adapter-rxjava3 Adapter: Coroutines suspend函数 (原生) 日志拦截器 logging-interceptor 作为addConverterFactory 选择一种 addInterceptor
上图展示了Retrofit、OkHttp、三种Converter、两种Adapter以及日志拦截器的依赖关系。实际项目只需按需选择一种Converter和一种Adapter,避免冗余。