我正在嘗試使用 Hilt 和 Retrofit2 創建帶有動態 URL 的 Post 請求。
我收到錯誤@Url cannot be used with @POST URL (parameter #1)
我也需要查詢是動態的
@POST("{id}")
suspend fun getConfiguration(
@Url url: String,
@Body configRequest: ConfigRequest,
@Query("id") id: String
): Config
建設者
@ExperimentalSerializationApi
@Provides
@Singleton
fun provideApi(@ApplicationContext context: Context): Api{
val contentType = "application/json".toMediaType()
val json = Json {
explicitNulls = false
coerceInputValues = true
ignoreUnknownKeys = true
}
return Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.client(RetrofitHelper.getOkHttpClient(context))
.addConverterFactory(json.asConverterFactory(contentType))
.build()
.create(Api::class.java)
}
有什么解決辦法嗎?
uj5u.com熱心網友回復:
@Url 是一個引數注解,允許傳遞一個端點的完整 URL,所以它不是基本 url,而是完整的端點 url,你不能將它與動態路徑一起使用@POST("{id}"),這個必須是這樣的,@POST()也@Query不能與 一起使用@Url,因此您有兩種解決方案:
- 第一種是
@Url自己保存并生成完整的 url(為查詢生成一個 url)并將其提供給 getConfiguration(url) 函式:
代碼:
@POST()
suspend fun getConfiguration(
@Url url: String,
): Config
- 第二個不推薦,但更簡單,它使用新的改造實體提供的其他基本 url 和其他 api 介面創建一個新的改造實體,并且您可以繼續使用
Query:
代碼:
@POST("{id}")
suspend fun getConfiguration(
@Body configRequest: ConfigRequest,
@Query("id") id: String
): Config
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/493685.html
