[英]How to add URL parameter in a Retrofit @GET request in Kotlin
I am currently trying to fetch a JSONArray from a server using Retrofit in Kotlin.我目前正在尝试使用 Kotlin 中的 Retrofit 从服务器获取 JSONArray。 Here is the interface I am using:
这是我正在使用的界面:
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)
}
}
}
the desired url is: https://someurl.com/coordsOfTrip?id=201
所需的 url 是:
https://someurl.com/coordsOfTrip?id=201
I am getting the following error message:我收到以下错误消息:
retrofit2.HttpException: HTTP 405 Method Not Allowed
retrofit2.HttpException: HTTP 405 方法不允许
I know the URL is working because I can access it via a browser.我知道 URL 正在工作,因为我可以通过浏览器访问它。
Can someone please help me identify what I am doing wrong?有人可以帮我确定我做错了什么吗?
Just change the parameter from只需将参数从
@GET("/coordsOfTrip{id}")
to至
@GET("/coordsOfTrip") // remove {id} part that's it
And you'd get the desired URL https://someurl.com/coordsOfTrip?id=201
你会得到想要的 URL
https://someurl.com/coordsOfTrip?id=201
If you want to use {id}
in GET()
then you've to use it like below如果你想在
GET()
中使用{id}
那么你必须像下面这样使用它
@GET("/coordsOfTrip{id}")
fun getTripCoord(
@Header("Authorization") token: String,
@Path("id") id: Int // use @Path() instead of @Query()
): Deferred<JSONArray>
But in your case it doesn't require.但在你的情况下,它不需要。 Follow the first method I mentioned.
按照我提到的第一种方法。
For more check Retorfit's official documentation URL Manipulation part更多请查看 Retorfit 的官方文档URL 操作部分
Replace代替
@GET("/coordsOfTrip{id}")
with:和:
@GET("/coordsOfTrip?id={id}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.