【问题标题】:Not able to post request using ktor client in kotlin js无法在 kotlin js 中使用 ktor 客户端发布请求
【发布时间】:2020-11-01 13:51:03
【问题描述】:

我正在尝试发出 http post 请求,但由于无法理解的原因而失败。

object KtorClient {
val client = HttpClient() {
    install(JsonFeature) {
        serializer = KotlinxSerializer()
    }
 }
}
suspend fun createOwner(url : String = "http://localhost:112/company/owner/register", ownerMapper: OwnerMapper) {
println(ownerMapper)
client.post<Unit>(url){
   body = ownerMapper
}
}

BlockquoteIllegalStateException {message_8yp7un$_0:“发送正文失败。内容类型:OwnerMapper 类,但应有 OutgoingContent。”,cause_th0jdv$_0:空,堆栈:“captureStack↵Exception↵RuntimeException↵IllegalSta…↵↵↵↵↵ ↵↵↵↵↵↵↵↵↵↵↵↵promiseReactionJob@[native code]”,名称:“IllegalStateException”}

添加序列化插件后,出现此错误:

“找不到类 OwnerMapper 的无参数序列化程序。对于泛型类,例如列表,请显式提供序列化程序。”

我已按照官方示例进行操作,但无法使其运行。正在使用 Kotlin/Js 及以上错误来自浏览器。

【问题讨论】:

    标签: ktor kotlin-js ktor-client


    【解决方案1】:
        val client = HttpClient() {
            install(JsonFeature){
                serializer = KotlinxSerializer()
            }
        }
    @Serializable
    data class OwnerLoginMapper(
        val email: String? = null,
        val username: String? = null,
        val number: String? = null,
        val credential: String
    )
    @Serializable
    data class Token(
        val token : String
    )
    var response = client.post<Token>(url){
        contentType(ContentType.Application.Json)
        body = ownerMapper
    }
    println(response.token)
    

    添加这些依赖项:

    implementation("io.ktor:ktor-client-json-js:1.3.2")
    implementation("io.ktor:ktor-client-serialization-js:1.3.2")
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime-js:0.20.0")
    

    应用这个插件:

        kotlin("plugin.serialization") version "1.3.70"
    

    PS:选择合适的版本号。

    【讨论】:

      【解决方案2】:

      您的OwnerMapper 课程是否标记为@Serializable

      如果不是——请标记为@Serializable

      如果是,请您尝试在没有 Ktor 的情况下重现第二个问题 ("Can't locate argument-less serializer for class OwnerMapper. For generic classes, such as lists, please provide serializer explicitly.")。在我看来,这似乎是序列化的问题,可能缺少一些依赖项。

      请看一下github问题:https://github.com/Kotlin/kotlinx.serialization/issues/278

      【讨论】:

      • 它被标记为可序列化,目前是手动序列化而不是在ktor客户端安装功能。由于手动 serializatioj 正在工作,所以我猜依赖是完整的,ktor 客户端似乎有问题。我会尝试分离出问题并调试。
      • @TarunChawla 你能附上你的项目的链接吗?
      • 我在这里做错了几件事。我会发布正确方法的答案。
      猜你喜欢
      • 2022-06-20
      • 2020-06-23
      • 2018-11-22
      • 2020-02-25
      • 2019-04-09
      • 2020-12-09
      • 2021-09-12
      • 2017-02-21
      • 2022-10-24
      相关资源
      最近更新 更多