如何在 Kotlin 的 Retrofit @GET 请求中添加 URL 参数
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 Method Not Allowed
我知道 URL 正在运行,因为我可以通过浏览器访问它。
有人可以帮我找出我做错了什么吗?
替换
@GET("/coordsOfTrip{id}")
与:
@GET("/coordsOfTrip?id={id}")
只需更改
中的参数
@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 Manipulation部分
我目前正在尝试使用 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 Method Not Allowed
我知道 URL 正在运行,因为我可以通过浏览器访问它。
有人可以帮我找出我做错了什么吗?
替换
@GET("/coordsOfTrip{id}")
与:
@GET("/coordsOfTrip?id={id}")
只需更改
中的参数@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 Manipulation部分