【问题标题】:How to change retrofit @GET programatically如何以编程方式更改改造@GET
【发布时间】: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


    【解决方案1】:

    为什么不使用改造后的@Query

    您可以将界面重新定义为:

    interface YoutubeListApi {
      @GET("search")
      fun getYoutubeVideos(
         @Query("part") part: String,
         @Query("q") query: String,
         @Query("key") key: String,
      ): Call<YoutubeAPIData>
    }
    

    然后您可以将其称为getYoutubeVideos("snippets", "eminem", "your key")getYoutubeVideos("snippets", "dog", "your key")

    如果你愿意,我认为你甚至可以在 URL 中硬编码一些值,但老实说,我认为你可以只使用 kotlin 默认值:

    interface YoutubeListApi {
      @GET("search")
      fun getYoutubeVideos(
         @Query("q") query: String,
         @Query("part") part: String = "snippet",
         @Query("key") key: String = "your key",
      ): Call<YoutubeAPIData>
    }
    

    只需传递查询getYoutubeVideos("eminem")。我没有仔细检查过,但我认为它可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-06
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多