You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Jetpack Compose中构建API接口时如何动态修改照片ID

解决方法:用@Path处理动态路径参数

你需要用Retrofit的@Path注解来处理URL路径里的动态照片ID,具体步骤如下:

  1. 修改@GET的路径,把固定的照片ID替换成占位符{photoId}
  2. 在方法参数里添加@Path("photoId")注解,绑定动态传入的ID值
  3. 注意返回类型不能是searchPhotos(这看起来像函数名),应该是你定义的用来映射接口返回数据的数据类(比如叫Photo)

修正后的完整API接口代码

@Singleton
interface PhotoViewApi {
    @GET("photos/{photoId}")
    suspend fun getSinglePhoto(
        @Path("photoId") photoId: String,
        @Query("client_id") clientId: String
    ): Photo
}

调用示例

调用时直接传入具体的照片ID和你的client_id即可:

// 比如获取HNCSCpWrVJA这张照片
api.getSinglePhoto("HNCSCpWrVJA", "你的Unsplash client_id")

额外优化建议

client_id不用每次作为参数传递,可以给Retrofit添加拦截器自动注入这个参数,让接口更简洁:

1. 定义拦截器

class UnsplashAuthInterceptor(private val clientId: String) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalUrl = chain.request().url
        val newUrl = originalUrl.newBuilder()
            .addQueryParameter("client_id", clientId)
            .build()
        val newRequest = chain.request().newBuilder().url(newUrl).build()
        return chain.proceed(newRequest)
    }
}

2. 构建Retrofit时添加拦截器

val retrofit = Retrofit.Builder()
    .baseUrl("https://api.unsplash.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .client(
        OkHttpClient.Builder()
            .addInterceptor(UnsplashAuthInterceptor("你的client_id"))
            .build()
    )
    .build()

3. 简化后的API接口

@Singleton
interface PhotoViewApi {
    @GET("photos/{photoId}")
    suspend fun getSinglePhoto(
        @Path("photoId") photoId: String
    ): Photo
}

内容的提问来源于stack exchange,提问作者Anand Kumar Mehta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 07:24:57