📦 环境搭建 · 依赖三件套

Retrofit + OkHttp + 转换器
⚡ 第2课 · 网络请求与数据加载实战
🔄

Retrofit

  • 类型安全的HTTP客户端
  • 注解驱动请求定义
  • 自动解析JSON/XML
🌐

OkHttp

  • 高效网络连接层
  • 连接池 & 缓存
  • 拦截器 & 日志
🔁

转换器

  • Gson / Moshi
  • 自动序列化
  • 可扩展

📋 依赖清单 (Gradle)

库名称 Gradle 依赖坐标 版本 (示例) 说明
Retrofit com.squareup.retrofit2:retrofit 2.9.0 核心库,自动解析接口
OkHttp com.squareup.okhttp3:okhttp 4.12.0 HTTP 引擎 & 连接池
Gson 转换器 com.squareup.retrofit2:converter-gson 2.9.0 Gson 序列化/反序列化
Moshi 转换器 com.squareup.retrofit2:converter-moshi 2.9.0 Moshi 替代方案 (可选)
OkHttp 日志拦截器 com.squareup.okhttp3:logging-interceptor 4.12.0 调试网络请求

📄 build.gradle (Module: app)

// Retrofit + OkHttp + Gson 转换器 (推荐组合)
dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.okhttp3:okhttp:4.12.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.12.0'

    // 选择 Gson 或 Moshi (二选一)
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    // implementation 'com.squareup.retrofit2:converter-moshi:2.9.0'
}
📐 Retrofit 依赖架构 📱 应用层 Activity / ViewModel 🔄 Retrofit 接口定义 + 动态代理 🔁 转换器 Gson / Moshi 🌐 OkHttp (HTTP 引擎 + 拦截器) 连接池 · 缓存 · 日志拦截器 ⬆️ 上层调用 ⬇️ 底层网络
💡 转换器选择建议: Gson 更广泛、易用;Moshi 在 Kotlin 中支持更好,且能处理空安全。两者选其一即可。 添加依赖时注意版本与 Retrofit 保持一致 (通常 2.9.0)。

⚙️ 快速初始化 (Kotlin/Java)

// Kotlin 示例 (使用 Gson 转换器)
val retrofit = Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .client(OkHttpClient.Builder()
        .addInterceptor(HttpLoggingInterceptor().apply {
            level = HttpLoggingInterceptor.Level.BODY
        })
        .build())
    .addConverterFactory(GsonConverterFactory.create())
    .build()

// Java 示例 (使用 Moshi 转换器)
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .client(new OkHttpClient.Builder()
        .addInterceptor(new HttpLoggingInterceptor()
            .setLevel(HttpLoggingInterceptor.Level.BODY))
        .build())
    .addConverterFactory(MoshiConverterFactory.create())
    .build();