【问题标题】:How to add params to url of http requests in ktor client如何在ktor客户端中将参数添加到http请求的url
【发布时间】:2022-12-26 09:12:12
【问题描述】:

我在使用 ktor 客户端向我的 http 请求添加 url 参数时遇到问题。

在我的 nodeJS 后端中,我期望在 url 中包含路径变量的 url,如下所示:

// plants.route.ts
this.router.delete('/plants/delete/:id', this.plantsController.delete);

我按照 ktor 客户端文档将参数添加到我的 http 请求 url,如下所述:https://ktor.io/docs/request.html 所以我的代码现在看起来像这样:

// HttpRoutes.kt
const val deletePlantRoute = "$backendUrl/plants/delete"

// PlantApiImplementation.kt
override suspend fun deletePlant(plantId: String): DeletePlantResponseDTO? {
  return try {
    client.delete {
      url(HttpRoutes.deletePlantRoute)
      parameter("id", plantId)
      contentType(ContentType.Application.Json)
    }
  } catch (error: Exception) {
    return null
  }
}

但是请求没有到达我的后端。

到目前为止,我已经尝试了以下 SO 线程的解决方案:

Example of URL builder in Ktor

How to pass query parameters to Ktor android

非常感谢任何指点!

【问题讨论】:

    标签: android ktor-client


    【解决方案1】:

    所以在做了一些挖掘和重新观看关于 ktor 客户端的 youtube 教程之后,我意识到我混淆了文档中的 query 参数和 path 参数。

    https://www.youtube.com/watch?v=3KTXD_ckAX0

    最终起作用的是直接在我的 api 调用中直接构建 url,如下所示:

    // PlantApiImplementation.kt
    override suspend fun deletePlant(plantId: String): DeletePlantResponseDTO? {
      return try {
        client.delete {
          // build the url directly with the needed params here
          url(HttpRoutes.deletePlantRoute + "/" + plantId)
          parameter("id", plantId)
          contentType(ContentType.Application.Json)
        }
      } catch (error: Exception) {
        return null
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-09
      • 2020-02-25
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      相关资源
      最近更新 更多