在Jetpack Compose中构建API接口时如何动态修改照片ID
解决方法:用
@Path处理动态路径参数 你需要用Retrofit的@Path注解来处理URL路径里的动态照片ID,具体步骤如下:
- 修改
@GET的路径,把固定的照片ID替换成占位符{photoId} - 在方法参数里添加
@Path("photoId")注解,绑定动态传入的ID值 - 注意返回类型不能是
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
相关产品推荐
相关产品推荐

