Android Retrofit用法详解

Retrofit 使用指南

Retrofit 是 Android 上最常用的网络请求库之一,它简化了 HTTP 请求的处理,支持 GET、POST、PUT、DELETE 等请求方式,并且可以配合 GsonMoshi 等解析 JSON 数据。

1. 添加依赖

build.gradle (Module 级) 中添加:

arduino 复制代码
dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0' // Gson 解析 JSON
}

2. 创建 API 接口

定义 API 接口,例如获取用户信息:

less 复制代码
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.PUT
import retrofit2.http.DELETE
import retrofit2.http.Body
import retrofit2.http.Path
import retrofit2.http.Header
​
interface ApiService {
    @GET("users/{id}")  // GET 请求
    fun getUser(@Path("id") userId: Int): Call<User>
​
    @POST("users")  // POST 请求
    fun createUser(@Body user: User): Call<User>
​
    @PUT("users/{id}")  // PUT 请求
    fun updateUser(@Path("id") userId: Int, @Body user: User): Call<User>
​
    @DELETE("users/{id}")  // DELETE 请求
    fun deleteUser(@Path("id") userId: Int): Call<Void>
​
    @GET("users/{id}")  // 添加自定义 Header
    fun getUserWithHeader(@Path("id") userId: Int, @Header("Authorization") token: String): Call<User>
}

3. 定义数据模型

kotlin 复制代码
data class User(
    val id: Int,
    val name: String,
    val email: String
)

4. 创建 Retrofit 实例

kotlin 复制代码
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
​
object RetrofitClient {
    private const val BASE_URL = "https://api.example.com/"
​
    val instance: ApiService by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ApiService::class.java)
    }
}

5. 发起网络请求

GET 请求

kotlin 复制代码
val call = RetrofitClient.instance.getUser(1)
call.enqueue(object : retrofit2.Callback<User> {
    override fun onResponse(call: Call<User>, response: retrofit2.Response<User>) {
        if (response.isSuccessful) {
            val user = response.body()
            println("用户信息: ${user?.name}, ${user?.email}")
        }
    }
​
    override fun onFailure(call: Call<User>, t: Throwable) {
        println("请求失败: ${t.message}")
    }
})

POST 请求

ini 复制代码
val newUser = User(0, "John Doe", "[email protected]")
val call = RetrofitClient.instance.createUser(newUser)

PUT 请求

ini 复制代码
val updatedUser = User(1, "Updated Name", "[email protected]")
val call = RetrofitClient.instance.updateUser(1, updatedUser)

DELETE 请求

ini 复制代码
val call = RetrofitClient.instance.deleteUser(1)

添加 Header 请求

ini 复制代码
val token = "Bearer your_token_here"
val call = RetrofitClient.instance.getUserWithHeader(1, token)

6. 使用协程 (Coroutine) 优化请求

将 API 接口修改为使用 suspend 函数:

kotlin 复制代码
interface ApiService {
    @GET("users/{id}")
    suspend fun getUser(@Path("id") userId: Int): User
}

在 ViewModel 中调用:

kotlin 复制代码
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
​
class UserViewModel : ViewModel() {
    fun fetchUser() {
        viewModelScope.launch {
            try {
                val user = RetrofitClient.instance.getUser(1)
                println("用户信息: ${user.name}, ${user.email}")
            } catch (e: Exception) {
                println("请求失败: ${e.message}")
            }
        }
    }
}

7. 总结

  • GET、POST、PUT、DELETE 基本请求
  • 添加 Header 请求
  • 使用 suspend + Coroutine 优化请求
相关推荐
会飞的鱼先生5 分钟前
Vue3的内置组件 -实现过渡动画 TransitionGroup
前端·javascript·vue.js·vue
晓得迷路了5 分钟前
10 分钟开发一个 Chrome 插件?Trae 让你轻松实现!
前端·javascript·trae
秋天的一阵风11 分钟前
Vue3探秘系列— 路由:vue-router的实现原理(十六-上)
前端·vue.js·面试
秋天的一阵风11 分钟前
Vue3探秘系列— 路由:vue-router的实现原理(十六-下)
前端·vue.js·面试
海底火旺31 分钟前
JavaScript中的Object方法完全指南:从基础到高级应用
前端·javascript·面试
海底火旺32 分钟前
JavaScript中的Symbol:解锁对象属性的新维度
前端·javascript·面试
天天扭码32 分钟前
一文吃透 ES6新特性——解构语法
前端·javascript·面试
Kagerou33 分钟前
组件测试
前端
JustHappy36 分钟前
啥是Hooks?为啥要用Hooks?Hooks该怎么用?像是Vue中的什么?React Hooks的使用姿势(上)
前端·vue.js·react.js
张可1 小时前
历时两年半开发,Fread 项目现在决定开源,基于 Kotlin Multiplatform 和 Compose Multiplatform 实现
android·前端·kotlin