繁体   English   中英

如何在 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 方法不允许

我知道 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM