| 注解 | 作用 | 示例 | 典型场景 |
|---|---|---|---|
| @Url | 完全动态的请求URL,覆盖BaseUrl | @GET fun getData(@Url url: String) |
下载文件、多BaseUrl切换 |
| @Path | 替换URL中的占位符 {xxx} | @GET("users/{id}") fun getUser(@Path("id") id: Long) |
RESTful API 资源路径 |
| @Query | 添加?key=value查询参数 | @GET("search") fun search(@Query("q") query: String) |
分页、过滤、搜索 |
| @QueryMap | 动态多个查询参数 | @GET("filter") fun filter(@QueryMap options: Map) |
复杂筛选条件 |
// ========== 动态URL @Url ========== @GET fun fetchImage(@Url imageUrl: String): Call<ResponseBody> // ========== 路径参数 @Path ========== @GET("users/{userId}/repos/{repoId}") fun getRepo( @Path("userId") userId: Long, @Path("repoId") repoId: String ): Call<Repo> // ========== 查询参数 @Query ========== @GET("products") fun searchProducts( @Query("keyword") keyword: String, @Query("page") page: Int = 1, @Query("sort") sort: String? = null ): Call<ProductResponse>
// Java 版本 —— 动态URL + 路径 + 查询 public interface ApiService { @GET Call<ResponseBody> downloadFile(@Url String fileUrl); @GET("users/{id}/posts") Call<List<Post>> userPosts(@Path("id") int userId); @GET("items") Call<ItemResponse> getItems( @Query("category") String category, @Query("page") int page, @Query("limit") int limit ); }