1.添加相关的依赖
dependencies {
implementation("com.squareup.retrofit2:retrofit:2.9.0") // 核心库
implementation("com.squareup.retrofit2:converter-gson:2.9.0") // Gson 解析
implementation("com.squareup.okhttp3:logging-interceptor:4.9.3") // 日志拦截器(可选)
}
2. 定义数据模型
data class User(
val id: Int,
val name: String,
val email: String
)
3. 定义 API 接口
使用 suspend
关键字让 Retrofit 与 Kotlin 协程结合:
interface ApiService {
@GET("users/{id}")
suspend fun getUser(@Path("id") userId: Int): User
@POST("users")
suspend fun createUser(@Body user: User): User
}
4. 创建 Retrofit 实例
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/") // 设置基础 URL
.addConverterFactory(GsonConverterFactory.create()) // 添加 JSON 解析
.build()
5. 创建 API Service
val apiService: ApiService = retrofit.create(ApiService::class.java)
6. 发起网络请求
使用协程进行异步请求(推荐):
suspend fun fetchUser(userId: Int) {
try {
val user = apiService.getUser(userId)
println("User Name: ${user.name}")
} catch (e: Exception) {
println("Error: ${e.message}")
}
}
7. 配置 OkHttp 拦截器(可选),设置拦截器是通过设置自定义的okhttpclient来实现的
如果需要日志输出,可以添加 OkHttp
的日志拦截器:
val loggingInterceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
val client = OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build()
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()