如何在Retrofit中动态修改@GET查询参数实现按关键词搜索YouTube视频
实现方案
步骤1:修改YoutubeListApi接口定义
删除@GET注解中写死的q=eminem参数,通过@Query注解声明动态的关键词参数:
interface YoutubeListApi { @GET("search?part=snippet&key=*my_key*") fun getYoutubeVideos(@Query("q") keyword: String): Call<YoutubeAPIData> }
步骤2:调整接口调用逻辑
给getVideosList方法添加入参接收搜索关键词,调用接口时传入该参数即可:
private fun getVideosList(keyword: String) { val videos = RetrofitInstance.youtubeapi.getYoutubeVideos(keyword) videos.enqueue(object : Callback<YoutubeAPIData?> { override fun onResponse(call: Call<YoutubeAPIData?>, response: Response<YoutubeAPIData?>) { val videosList = response.body()?.items if (videosList != null) { for(video in videosList) { Log.d("title", video.snippet.title) } } } override fun onFailure(call: Call<YoutubeAPIData?>, t: Throwable) { Toast.makeText(applicationContext, "Unable to fetch results!", Toast.LENGTH_SHORT).show() Log.d("APIError",t.toString()) } }) }
使用方式
需要搜索对应关键词时直接传入参数调用即可:
- 搜索eminem:
getVideosList("eminem"),生成的请求路径为search?part=snippet&q=eminem&key=*my_key* - 搜索dog:
getVideosList("dog"),生成的请求路径为search?part=snippet&q=dog&key=*my_key*
可选优化
如果后续需要动态调整其他参数(比如key、part参数),也可以用同样的@Query方式处理,示例:
// 把key也改为动态传入的版本 interface YoutubeListApi { @GET("search") fun getYoutubeVideos( @Query("part") part: String = "snippet", @Query("q") keyword: String, @Query("key") apiKey: String ): Call<YoutubeAPIData> }
内容的提问来源于stack exchange,提问作者Chrizlove
相关产品推荐
相关产品推荐

