kotlin retrofit API接口中需要传递参数如何传递,如何调用
时间: 2025-01-25 15:13:47 浏览: 23
在Kotlin中使用Retrofit进行API接口调用时,传递参数可以通过多种方式实现。以下是一些常见的方法和步骤:
1. 定义API接口
首先,定义一个接口来描述你的API端点。你可以使用@GET、@POST等注解来指定HTTP方法和端点路径。
import retrofit2.http.GET
import retrofit2.http.Query
interface ApiService {
@GET("users")
suspend fun getUsers(@Query("page") page: Int): Response<UserResponse>
}
2. 创建Retrofit实例
接下来,创建一个Retrofit实例并配置它以使用你的API接口。
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val apiService = retrofit.create(ApiService::class.java)
3. 调用API接口
最后,使用定义好的API接口进行网络请求。
import kotlinx.coroutines.*
suspend fun fetchUsers(page: Int) {
try {
val response = apiService.getUsers(page)
if (response.isSuccessful) {
val users = response.body()
// 处理用户数据
} else {
// 处理错误响应
}
} catch (e: Exception) {
// 处理异常
}
}
// 在协程中调用
GlobalScope.launch {
fetchUsers(1)
}
4. 传递复杂参数
如果需要传递更复杂的参数,可以使用@Body注解传递一个数据类。
import retrofit2.http.Body
import retrofit2.http.POST
data class User(val name: String, val email: String)
interface ApiService {
@POST("users")
suspend fun createUser(@Body user: User): Response<UserResponse>
}
// 调用接口
suspend fun createUser(user: User) {
try {
val response = apiService.createUser(user)
if (response.isSuccessful) {
val createdUser = response.body()
// 处理创建的用户数据
} else {
// 处理错误响应
}
} catch (e: Exception) {
// 处理异常
}
}
5. 动态URL参数
如果需要动态传递URL参数,可以使用@Path注解。
import retrofit2.http.Path
interface ApiService {
@GET("users/{id}")
suspend fun getUser(@Path("id") id: Int): Response<UserResponse>
}
// 调用接口
suspend fun fetchUser(id: Int) {
try {
val response = apiService.getUser(id)
if (response.isSuccessful) {
val user = response.body()
// 处理用户数据
} else {
// 处理错误响应
}
} catch (e: Exception) {
// 处理异常
}
}
通过以上步骤,你可以在Kotlin中使用Retrofit进行API接口调用并传递参数。
相关推荐


















