MST

星途 面试题库

面试题:Kotlin中如何在Ktor框架里处理请求参数

假设你正在使用Kotlin与Ktor框架开发一个Web应用,当客户端发送一个带有查询参数和表单参数的HTTP请求时,在Ktor中应该如何获取并处理这些参数?请写出示例代码。
13.2万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试

在Ktor中,可以通过call.parameters获取查询参数,通过call.receiveParameters()获取表单参数。以下是示例代码:

import io.ktor.application.*
import io.ktor.http.*
import io.ktor.request.*
import io.ktor.response.*
import io.ktor.routing.*

fun Application.module() {
    routing {
        post("/example") {
            // 获取查询参数
            val queryParam = call.parameters["queryParam"]
            // 获取表单参数
            val formParameters = call.receiveParameters()
            val formParam = formParameters["formParam"]

            call.respondText("Query Param: $queryParam, Form Param: $formParam", contentType = ContentType.Text.Plain)
        }
    }
}

上述代码创建了一个Ktor应用,在/example路径处理POST请求,分别获取查询参数queryParam和表单参数formParam,并返回给客户端。