我在使用 NASA APOD API 创建正确的 @GET 请求时遇到问题。根据文档,我可以使用“日期”参数向请求添加特定日期,例如 date=2020-03-21: https://api.nasa.gov/planetary/apod?date=2020- 03-21&api_key=DEMO_KEY 在这种情况下,一切正常。但是,当我尝试修改加载昨天照片的请求时,出现错误。我必须以某种方式将昨天的日期传递给“date”参数,但我不明白如何做到这一点:https://api.nasa.gov/planetary/apod?date=*YESTERDAY_DATE_HERE*&api_key=DEMO_KEY
我尝试创建 LocalDate 变量,但收到构建错误:注释参数必须是编译时常量
我将不胜感激任何帮助!
我的代码:
interface NasaApiService {
val yesterdayDate: LocalDate
get() = LocalDate.now().minusDays(1)
@GET("planetary/apod?date=$yesterdayDate&api_key=" + BuildConfig.NASA_API_KEY)
fun getYesterdayPhoto(): Call<NasaPhoto>
companion object {
private const val BASE_URL = "https://api.nasa.gov/"
fun returnToVmFunction(): NasaApiService {
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
return retrofit.create(NasaApiService::class.java)
}
}
}
您确实只能将编译时常量作为参数传递给注释,并且参数化字符串不是编译时常量。使用 Retrofit 的
@Query
参数代替:
@GET("planetary/apod")
fun getYesterdayPhoto(
@Query("date") date: String,
@Query("api_key") apiKey: String,
): Call<NasaPhoto>
@Value("${stripe.key}") 私有 val stripeKey:字符串? = 空
通常在 $ 前面使用 \ 可以解决问题