【问题标题】:@Path as optional param?@Path 作为可选参数?
【发布时间】:2019-09-24 16:56:48
【问题描述】:

在我的 android 项目中,我使用 Retrofit:

@POST("/correspondents/{correspondent_id}")
    fun updateCorrespondent(@Path("correspondent_id") correspondentId: String, @Body body: JsonElement): Call<Void>

所以我像这样从客户那里打电话:

 fun updateCorrespondent(correspondent: Correspondent, callback: Callback<Void>) {
        val call = myRestClient.updateCorrespondent(correspondent.id, correspondent.toUpdateJson())
        call.enqueue(callback)
    }

很好,很好用。

但我需要做@Path("correspondent_id") 可选。

我需要像这样从客户那里打电话:

fun updateCorrespondent(correspondent: Correspondent, callback: Callback<Void>) {
        val call = tangoRestClient.updateCorrespondent(correspondent.toUpdateJson())        
        call.enqueue(callback)
    }

有可能吗?

现在我使用两种不同的方法:

@POST("/correspondents/{correspondent_id}")
    fun updateCorrespondent(@Path("correspondent_id") correspondentId: String, @Body body: JsonElement): Call<Void>

    @POST("/correspondents/create")
    fun createCorrespondent(@Body body: JsonElement): Call<Void>

是否可以只使用一种方法和可选的@Path

【问题讨论】:

  • 你的 API 端点支持这个吗?您的 api 端点中的通讯者 ID 的默认值是什么
  • @POST("/correspondents/{correspondent_id}") 有趣的 updateCorrespondent(@Path("correspondent_id") 通讯员Id: String?="create", @Body body: JsonElement): Call将默认值设置为“create” 现在您可以在没有相应 ID 的情况下调用此方法,并且当您需要传递不同的 id 时,请传递新的对应 ID
  • @KishanMaurya 我试试这个:myRestClient.updateCorrespondent(correspondent.toUpdateJson()),但我得到编译错误:Required String?, Found JsonElement
  • mtRestClient.updateCorrespondent(body = contacts.toUpdateJson())
  • 我正在发布这个答案。如果解决了,请点赞

标签: android kotlin retrofit2


【解决方案1】:
@POST("/correspondents/{correspondent_id}") fun updateCorrespondent(@Path("correspondent_id") correspondentId: String?="create", @Body body: JsonElement): Call<Void>

当您不需要通讯录时,请像这样调用

mtRestClient.updateCorrespondent(body = correspondent.toUpdateJson())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 2016-11-02
    • 2014-08-05
    • 2012-05-22
    • 2015-08-12
    • 1970-01-01
    相关资源
    最近更新 更多