Sag333ar
06/24/2020, 3:57 PMembeddedServer(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", "<http://some.server.com|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)
If step 9 is executed first, step 10- doesn't set the headers to response. If step 10 is executed first, step-9 response body isn't set.
How do I send both together - response body & response headers?rt
06/24/2020, 9:44 PMrespond*
should usually come last. setting headers beforehand also should work as intended:
call.response.header("foo", "bar")
call.respondText("""{"a":1}""", ContentType.Application.Json, HttpStatusCode.OK)
will both set header and return expected responseSag333ar
06/24/2020, 11:59 PMkqr
06/25/2020, 6:45 AMrt
06/25/2020, 11:17 AMSag333ar
06/25/2020, 2:01 PM