Kotlin ktor jetty 修改响应标头



这是我到目前为止尝试过的。

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- 不会将标头设置为响应。 如果首先执行步骤 10,则不会设置步骤 9 响应正文。

如何同时发送两者 - 响应正文和响应标头?

我只有一半的答案,对不起。

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

提交的响应将阻止您修改响应标头。

call.response.header("Set-Cookie", ...)应该只设置一个标题,而不做任何其他事情。

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

最新更新