【发布时间】:2021-09-30 22:36:45
【问题描述】:
我有一个应用程序,我使用 youtube api 并使用改造发出获取请求,现在我想获取特定关键字的视频列表,但为此我必须每次都使用不同的获取请求,所以我该怎么做以编程方式更改获取请求
API调用代码
private fun getVideosList() {
val videos = RetrofitInstance.youtubeapi.getYoutubeVideos()
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())
}
})
}
改造实例
object RetrofitInstance {
const val BASE_URL = "https://www.googleapis.com/youtube/v3/"
private val retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val youtubeapi: YoutubeListApi by lazy {
retrofit.create(YoutubeListApi::class.java)
}}
API接口代码
interface YoutubeListApi {
@GET("search?part=snippet&q=eminem&key=*my_key*")
fun getYoutubeVideos(): Call<YoutubeAPIData>}
现在我想要的是更改 api 界面中的 @GET("search?part=sn-p&q=eminem&key=my_key") 以便如果关键字是 eminem 它应该是搜索?part=sn-p&q=eminem&key=my_key 如果关键字是 dog 它应该是 search?part=sn-p&q=dogkey=my_key
【问题讨论】:
标签: retrofit2