[英]How to add URL parameter in a Retrofit @GET request in Kotlin
我目前正在嘗試使用 Kotlin 中的 Retrofit 從服務器獲取 JSONArray。 這是我正在使用的界面:
interface TripsService {
@GET("/coordsOfTrip{id}")
fun getTripCoord(
@Header("Authorization") token: String,
@Query("id") id: Int
): Deferred<JSONArray>
companion object{
operator fun invoke(
connectivityInterceptor: ConnectivityInterceptor
):TripsService{
val okHttpClient = OkHttpClient.Builder().addInterceptor(connectivityInterceptor).build()
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl("https://someurl.com/")
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(TripsService::class.java)
}
}
}
所需的 url 是: https://someurl.com/coordsOfTrip?id=201
我收到以下錯誤消息:
retrofit2.HttpException: HTTP 405 方法不允許
我知道 URL 正在工作,因為我可以通過瀏覽器訪問它。
有人可以幫我確定我做錯了什么嗎?
只需將參數從
@GET("/coordsOfTrip{id}")
至
@GET("/coordsOfTrip") // remove {id} part that's it
你會得到想要的 URL https://someurl.com/coordsOfTrip?id=201
如果你想在GET()
中使用{id}
那么你必須像下面這樣使用它
@GET("/coordsOfTrip{id}")
fun getTripCoord(
@Header("Authorization") token: String,
@Path("id") id: Int // use @Path() instead of @Query()
): Deferred<JSONArray>
但在你的情況下,它不需要。 按照我提到的第一種方法。
更多請查看 Retorfit 的官方文檔URL 操作部分
代替
@GET("/coordsOfTrip{id}")
和:
@GET("/coordsOfTrip?id={id}")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.