🔗 URL 操作 · 动态/路径/查询

Retrofit 实战
🎯 @Url 动态URL · @Path 路径参数 · @Query 查询参数 📱 Android / Java 网络编程
注解作用示例典型场景
@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)
复杂筛选条件

Retrofit 接口定义 (Kotlin)

// ========== 动态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>
@Url 动态完整URL 覆盖 BaseUrl @Path 路径占位符 /users/{id} @Query ?key=value 查询参数 ⚡ 灵活组合 · 动态请求 · 类型安全

🎒 @Url 小贴士

  • 必须是完整的 http/https 链接
  • 可配合 @GET、@POST 等使用
  • 常用于文件下载/多BaseUrl

📌 @Path 注意

  • 占位符 { } 必须与 @Path 名称一致
  • 自动进行URL编码
  • 路径参数不可为null

🧩 @Query 技巧

  • 可添加默认值 (如 page=1)
  • @QueryMap 动态传参
  • 值为 null 自动忽略

Java 接口示例 (Android)

// 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
    );
}