Retrofit的使用步骤

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()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值