安卓使用Retrofit进行网络请求(Kotlin)

最近在在学习kotlin,在使用okhttp时发现一个比Okhttp更好用的第三方库,最后了解后发现Retrofit就是基于Okhttp写的,然而作者还是同一家公司squareup。话不多说,直接开始!

目录

一、引入依赖

二、创建数据模型

三、定义Retrofit API接口

四、初始化Retrofit实例

五、发起网络请求

(一)使用enqueue

(二)使用协程

1.首先添加“kotlinx-coroutines”依赖:

2.修改ApiServicej接口,将Call替换成suspend函数

3.在ViewModel或使用协程的地方进行调用

六、处理API错误

一、引入依赖

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,我相信你可以实现更加简洁和易读的代码结构。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大菠萝‍

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值