kotlin retrofit实现拼接在接口里的参数
时间: 2025-01-25 21:14:11 浏览: 23
在Kotlin中使用Retrofit实现接口里的参数拼接,可以通过以下步骤完成:
- 添加依赖:首先,确保你的项目中已经添加了Retrofit和Gson的依赖。
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}
- 定义API接口:在接口中使用
@Path
注解来拼接参数。
import retrofit2.http.GET
import retrofit2.http.Path
interface ApiService {
@GET("users/{user}/repos")
suspend fun listRepos(@Path("user") user: String): List<Repo>
}
- 创建Retrofit实例:在Kotlin中,可以使用
Retrofit.Builder
来创建Retrofit实例。
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
val retrofit = Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val apiService = retrofit.create(ApiService::class.java)
- 调用接口:使用协程来调用接口方法。
import kotlinx.coroutines.runBlocking
runBlocking {
try {
val repos = apiService.listRepos("octocat")
repos.forEach {
println(it.name)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
通过以上步骤,你可以在Kotlin中使用Retrofit实现接口里的参数拼接。
相关推荐


















