https://kotlinlang.org logo
Title
s

Sag333ar

06/24/2020, 3:57 PM
Greetings. Problem: I can't modify Response headers - Kotlin - Ktor - Jetty Server Attempt: Here is the code which I've tried.
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", "<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?
r

rt

06/24/2020, 9:44 PM
respond*
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 response
s

Sag333ar

06/24/2020, 11:59 PM
@rt I tried that too. The moment I set header, respondText won't be executed.
k

kqr

06/25/2020, 6:45 AM
#ktor ?
r

rt

06/25/2020, 11:17 AM
I ran that code before posting it, it works. Make sure you don't have anything else suspicious around it or try to simplify your problem to a minimal self-contained example because it seems like you may have issues somewhere else
s

Sag333ar

06/25/2020, 2:01 PM
That's the only piece of code I've 🙂 I'm still experimenting. I guess it's the issue with setting Content-Type header before sending response with response. I'll try & update my message here.
That worked. Thanks 🙏 🤝