【问题标题】:Why Ktor Post Request freeze app, but Get doesn't freeze it?为什么 Ktor Post Request 冻结应用程序,但 Get 不冻结它?
【发布时间】:2021-08-16 15:07:07
【问题描述】:
suspend fun main(args: Array<String>) {
    val client = HttpClient(CIO)
    embeddedServer(Netty, 6001) {
        routing {
            get("/") {
                println(call.request.toLogString())
                call.respondText("Please use POST method", status = HttpStatusCode.BadRequest)
            }
            post("/") {
                call.respondText("{}")
                val params = call.receiveText()
                println(params)
                delay(200)
                println("pre response")
                val response2: HttpResponse = client.post("https://google.com")
                println(response2.status)
                val response: HttpResponse = client.post("https://discord.com/api/webhooks/discord/webhookurl") {
                    body = "{\"content\": \"$params\"}"
                }
                println("after")
                println("response: ${response.receive<String>()}")
            }
        }
    }.start(true)
}

此代码打印到控制台:

{"test":"test"}
pre response

应用程序冻结。 如果我尝试向 google 或 discord 发送 GET 请求,这将起作用并且不会冻结。 为什么?

【问题讨论】:

  • 我在pre response 之后得到了ClientRequestException: Client request(https://google.com/) invalid: 405 Method Not Allowed。如果我为客户端将expectSuccess 设置为false,那么应用程序只会打印:{"test":"test"}\n pre response\n 405 Method Not Allowed\n after\n response: {"webhook_id": ["Value \"discord\" is not snowflake."]}\n
  • 您在服务器日志中看到了什么?请通过editing您的问题添加日志。

标签: kotlin ktor


【解决方案1】:

对 google.com 的发布请求引发异常:

client.post("https://google.com")

如果您在日志中看到此警告:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

然后你应该在你的项目中添加slf4j 依赖来启用日志记录:

implementation("org.slf4j:slf4j-simple:(version)")

之后,您将在服务器日志中看到错误的完整堆栈跟踪:

[eventLoopGroupProxy-4-1] ERROR ktor.application - Unhandled: POST - /
    io.ktor.client.features.ClientRequestException:
        Client request(https://google.com/) invalid: 405 Method Not Allowed.
        ...
        ...

【讨论】:

  • 如果这是对您问题的回答,那么您可以mark 将回答设为“已接受”。
猜你喜欢
  • 2022-12-09
  • 1970-01-01
  • 1970-01-01
  • 2021-08-18
  • 2020-02-23
  • 2022-07-26
  • 2023-01-27
  • 2019-11-04
  • 2015-05-09
相关资源
最近更新 更多