【问题标题】:How to pass a url parameter with Ktor Kotlin and HttpClient?如何使用 Ktor Kotlin 和 HttpClient 传递 url 参数?
【发布时间】:2022-11-03 14:12:54
【问题描述】:

我想使用 Google Books API,因此我有一个搜索字段可以通过它的 isbn 来查找一本书。我将 Kotlin 与 Ktor 一起使用,前端与 HTML/CSS 一起使用。使用 Routing 类,我想在单击搜索字段时调用 api 并传递参数以构建整个 url 并返回 json 数据。

问题是:当我尝试通过读取表单参数来传递路由类中的参数时,没有任何反应,并且页面没有重定向到我的搜索页面。

那么如何构建它以在搜索字段中传递 isbn 并为 API 调用构建正确的 url?

路由.kt:

fun Application.configureRouting() {

routing {
    static("/static") {
        resources("files")
    }
    get("/") {
        call.respondRedirect("books")
    }

    route("search") {
        get {
            call.respond(FreeMarkerContent("search.ftl", model = null))
        }

        get("field") {
            val formParameters = call.receiveParameters()
            val isbn = formParameters.getOrFail("isbn").toLong()
            val client = HttpClient(CIO)
            val response: HttpResponse = client.get("https://www.googleapis.com/books/v1/volumes?q=isbn:$isbn")
            println(response.status)
            val stringBody: String = response.body()
            println(stringBody)
            client.close()
            call.respondRedirect("/search")
        }
    }
}
}

当我删除这两行并直接在 url 中传递 isbn 时,我得到 json 响应:

val formParameters = call.receiveParameters()
val isbn = formParameters.getOrFail("isbn").toLong()

测试网址:

 val response: HttpResponse = client.get("https://www.googleapis.com/books/v1/volumes?q=isbn:9783453528420")

搜索.ftl:

<#import "_layout.ftl" as layout />
<@layout.header>
    <div>
        <div class="text-center">
            <h1 class="display-4">Search</h1>
        </div>
        <div class="container">
            <div class="row">
                <div class="form-group has-search">
                    <span class="fa fa-search form-control-feedback"></span>
                    <form action="/search/field" method="get">
                    <input type="text" class="form-control" name="isbn">
                    </form>
                </div>
            </div>
</@layout.header>

【问题讨论】:

    标签: html kotlin ktor ktor-client


    【解决方案1】:

    表单作为 GET 提交。 GET 没有表单参数,但有查询参数。

    服务器端代码正在执行 GET,但它正在尝试读取表单参数。

    尝试将行更改为

    val isbn = call.request.queryParameters.getOrFail("isbn").toLong()
    

    我没有测试过这段代码,但解决方案是使用queryParameters

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-26
      • 2021-03-01
      • 2021-03-21
      • 2012-10-16
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多