如何在 Kotlin 的 Retrofit @GET 请求中添加 URL 参数

Phi*_*ais 0 android kotlin retrofit retrofit2

我目前正在尝试使用 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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

所需的网址是: https://someurl.com/coordsOfTrip?id=201

我收到以下错误消息:

retrofit2.HttpException:不允许使用 HTTP 405 方法

我知道 URL 有效,因为我可以通过浏览器访问它。

有人可以帮我确定我做错了什么吗?

Sha*_*nth 5

只需将参数从

@GET("/coordsOfTrip{id}")
Run Code Online (Sandbox Code Playgroud)

@GET("/coordsOfTrip")   // remove {id} part that's it
Run Code Online (Sandbox Code Playgroud)

你会得到想要的 URL https://someurl.com/coordsOfTrip?id=201

如果你想使用{id}GET()那么你必须像下面那样使用它

@GET("/coordsOfTrip{id}")
fun getTripCoord(
        @Header("Authorization") token: String,
        @Path("id") id: Int    // use @Path() instead of @Query()
): Deferred<JSONArray>
Run Code Online (Sandbox Code Playgroud)

但在你的情况下,它不需要。按照我提到的第一种方法。

更多请查看 Retorfit 的官方文档URL Manipulation部分

  • 从文档来看,这似乎是正确的解决方案: @GET("/coordsOfTrip") fun getTripCoord(@Header("Authorization") token: String, @Query("id") id:Int); (2认同)