Kotlin that jetty modify response headers

Kotlin ktor jetty modify response headers

这是我目前尝试过的方法。

embeddedServer(Jetty, 9000) {
    install(ContentNegotiation) {
        gson {}
    }
    routing {
        post("/account/login") {
            // 1. Create URL
            val url = URL("http://some.server.com/account/login")
            // 2. Create HTTP URL Connection
            var connection: HttpURLConnection = url.openConnection() as HttpURLConnection
            // 3. Add Request Headers
            connection.addRequestProperty("Host", "some.server.com")
            connection.addRequestProperty("Content-Type", "application/json;charset=utf-8")
            // 4. Set Request method
            connection.requestMethod = "POST"
            // 5. Set Request Body
            val requestBodyText = call.receiveText()
            val outputInBytes: ByteArray = requestBodyText.toByteArray(Charsets.UTF_8)
            val os: OutputStream = connection.getOutputStream()
            os.write(outputInBytes)
            os.close()
            // 6. Get Response as string from HTTP URL Connection
            val string = connection.getInputStream().reader().readText()
            // 7. Get headers from HTTP URL Connection
            val headerFields =  connection.headerFields
            // 8. Get Cookies Out of response
            val cookiesHeader = headerFields["Set-Cookie"]?.joinToString { "${it};" } ?: ""
            // 9. Respond to Client with JSON Data
            call.respondText(string, ContentType.Text.JavaScript, HttpStatusCode.OK)
            // 10. Add Response headers
            call.response.header("Set-Cookie", cookiesHeader)
        }
    }
}.start(wait = false)

如果第9步先执行,第10步-不会设置headers响应。 如果第 10 步先执行,第 9 步响应 body 未设置。

如何将两者一起发送 - 响应 body 和响应 headers?

我只回答了一半,抱歉。

似乎 call.respondText(...., HttpStatusCode.OK) 将提交响应(因为它已将状态代码“OK”声明为参数)。

提交的响应会阻止您修改响应 headers。

call.response.header("Set-Cookie", ...) 应该只设置一个 header,什么都不做。

从一般 HTTP 服务器的角度来看,您希望首先设置响应状态代码,然后响应 headers,然后生成响应 body 内容,然后(可选)生成响应尾部。