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

Kotlin Retrofit如何使用Intent获取的apikey发起带access_token的GET请求

解决方案

1. 修改API接口定义

移除Alerts25Interface中硬编码的access_token参数,通过Retrofit提供的@Query注解声明动态查询参数:

interface Alerts25Interface {
    @GET("Alerts")
    // 声明access_token为动态传入的查询参数
    fun getData(@Query("access_token") apiKey: String): Call<List<Alerts25DataClass>>
}

Retrofit会自动将@Query声明的参数拼接为请求URL的查询字段,最终生成的请求地址格式为https://{cname}.something.com/api/Alerts?access_token={传入的apikey},和你之前硬编码的请求格式完全一致。

2. 调用接口时传入动态apikey

修改getAlert25Data()方法中调用getData()的代码,将从Intent中获取到的apikey作为参数传入即可:

// 原有代码获取apikey不变
val apikey:String = intent.getStringExtra("apikey").toString()
// ... 省略Retrofit实例构建代码
// 调用时传入apikey
val retrofitData = retrofitBuilder.getData(apikey)

可选优化:如果你的项目中存在多个接口都需要携带access_token参数,也可以通过OkHttp拦截器统一添加,无需每个接口都声明@Query参数,减少重复代码。

内容的提问来源于stack exchange,提问作者manjesh23

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 17:15:03