最近在在学习kotlin,在使用okhttp时发现一个比Okhttp更好用的第三方库,最后了解后发现Retrofit就是基于Okhttp写的,然而作者还是同一家公司squareup。话不多说,直接开始!
目录
2.修改ApiServicej接口,将Call替换成suspend函数
一、引入依赖
dependencies{
implementation("com.squareup.retrofit2:retroffit:2.9.0")
implementation("com.squareup.retrofit2:converter-gson:2.9.0")
}
二、创建数据模型
定义与json响应对应的数据模型类,使用@SerializedName注解是将json字段映射到Kotlin属性
data class User(
@SerializedName("id") val id : Int,
@SerializedName("name") val name : String,
@SerializedName("email") val email : String
)
三、定义Retrofit API接口
定义一个接口,用于声明API的端点和请求方法,使用@GET,@POST,@PUT,@DELETE等注解来指定HTTP请求类型
interface ApiService{
@GET("users/{id}")
fun getUser(@Path("id") userId: Int): Call<User>
}
四、初始化Retrofit实例
在应用中创建并初始化Retrofit实例,指定base Url和转换器工厂
object RetrofitClient{
private const val BASE_URL ="https://api.example.com/"
val instance : Retrofit by lazy{
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val apiService : ApiService by lazy{
instance.craeate(ApiService::class.java)
}
}
五、发起网络请求
在ViewModel或者Activity中调用Api,并处理响应,可以选择“enqueue”进行异步请求,或者使用协程进行更简洁的处理
(一)使用enqueue
fun fetchUser(userId : Int){
RetrofitClient.apiService.getUser(userid).enqueue(object: CallBack<User>{
override fun onResponse(call: Call<User>,response<User>){
if(response.isSuccessFul){
val user =response.body()
//处理用户数据
Log.d("Retrofit","User ${user?.name}")
}else{
Log.d("Retrofit","Request failed with code ${response.code()}")
}
}
override fun onFailure(call: Call<User>,t: Throwable){
Log.d("Retrofit","Network request failed")
}
})
}
(二)使用协程
协程方式简洁易读,推荐使用
1.首先添加“kotlinx-coroutines”依赖:
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.1")
2.修改ApiServicej接口,将Call<T>替换成suspend函数
interface ApiService{
@GET("users/{id}")
suspend fun getUser(@Path(""id) userId: Int):User
}
3.在ViewModel或使用协程的地方进行调用
suspend fun fetchUser(userId :Int): User?{
return try{
withContext(Dispatchers.IO){
RetrofitClient.apiService.getUser(userId)
}
} catch (e : Exception){
Log.d("Retrofit","Error fetching user")
null
}
}
六、处理API错误
确保在网路请求时处理API错误,如4XX/5XX的状态码,网络连接等问题可以使用"response.code()"来检查状态码并做相应处理。
七、结论
Retrofit提供了简洁的API能够让Dev轻松发起网络请求。通过配合Kotlin协程,以及MVVM,我相信你可以实现更加简洁和易读的代码结构。