⚡ 第2课 · 网络请求与数据加载实战
🔄
Retrofit
- 类型安全的HTTP客户端
- 注解驱动请求定义
- 自动解析JSON/XML
🌐
OkHttp
- 高效网络连接层
- 连接池 & 缓存
- 拦截器 & 日志
📋 依赖清单 (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)
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'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}
💡 转换器选择建议:
Gson 更广泛、易用;Moshi 在 Kotlin 中支持更好,且能处理空安全。两者选其一即可。
添加依赖时注意版本与 Retrofit 保持一致 (通常 2.9.0)。
⚙️ 快速初始化 (Kotlin/Java)
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.client(OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
})
.build())
.addConverterFactory(GsonConverterFactory.create())
.build()
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();