如何在Retrofit中基于ID实现动态API端点?
问题:Retrofit如何实现动态API端点URL?
我希望能使用动态API端点URL获取特定数据,目前已能在@GET("endpoint")中使用固定URL且可正常运行,但不知道如何实现动态调用。我的WebService类代码如下:
class WebService { private lateinit var api: MyApi init { val retrofit = Retrofit.Builder() .baseUrl("https://myUrl.com/") .addConverterFactory(GsonConverterFactory.create()) .build() api = retrofit.create(MyApi::class.java) } suspend fun getData(): MyResponse { return api.getData() } interface MyApi { @GET("/my/endpoint/1") suspend fun getData(): MyResponse } }
请问该如何修改代码,使其支持@GET("/my/endpoint/MY_ID")这种动态形式?
解决方法
要实现动态端点,你需要借助Retrofit的@Path注解替换URL中的动态部分,具体步骤如下:
1. 修改MyApi接口
将@GET注解里的固定ID替换为占位符{id},并在方法参数中添加@Path("id")注解绑定动态值:
interface MyApi { // 用{id}作为动态占位符,@Path注解将参数值注入到对应位置 @GET("/my/endpoint/{id}") suspend fun getData(@Path("id") id: Int): MyResponse }
注:如果你的ID是字符串类型,将参数类型改为
String即可。
2. 修改WebService的getData方法
让getData方法接收ID参数,并传递给API接口的对应方法:
class WebService { private lateinit var api: MyApi init { val retrofit = Retrofit.Builder() .baseUrl("https://myUrl.com/") .addConverterFactory(GsonConverterFactory.create()) .build() api = retrofit.create(MyApi::class.java) } // 新增id参数,传递给api.getData suspend fun getData(id: Int): MyResponse { return api.getData(id) } }
3. 调用示例
现在你可以在调用时传入具体ID,比如:
val webService = WebService() val response = webService.getData(123) // 实际请求URL为https://myUrl.com/my/endpoint/123
内容的提问来源于stack exchange,提问作者user21966091
相关产品推荐
相关产品推荐

