【问题标题】:Kotlin Spring Boot form-urlencoded POST requests with a Map带有 Map 的 Kotlin Spring Boot form-urlencoded POST 请求
【发布时间】:2017-12-02 05:35:13
【问题描述】:

我刚刚开始使用 Kotlin 和 Spring Boot,并决定编写一个简单的端点来接收表单 urlencoded POST 请求。我不想为正文编写一个实际的数据类,所以我尝试只为正文使用一个 Map,希望我可以访问键/值对。我第一次尝试:

@RestController
class MyController {

    @RequestMapping(value = "/endpoint", method = arrayOf(RequestMethod.POST),
            consumes = arrayOf("application/x-www-form-urlencoded"))
    fun myEndpoint(@RequestBody body: Map<String,String>): String {

        // Do stuff
    }
}

但这导致了关于不受支持的媒体类型的 415 错误...我读到这是由于使用了 @RequestBody 和 form-urlencoded POST。我随后尝试改用 @ModelAttribute 但后来收到了

无法实例化[java.util.Map]:指定的类是一个接口

不足为奇,因为我完全是在黑客攻击。我也尝试过不为正文添加任何注释,但没有注入任何表单参数。我知道我可以添加一个数据类来解决这个问题,但我想知道这是否可以使用 Map 来完成,因为我之前在 Java 中做过类似的事情。

谢谢。

【问题讨论】:

    标签: spring-boot kotlin


    【解决方案1】:

    你需要用@RequestParam注释你的body参数

        @RequestMapping(value = "/endpoint", method = [(RequestMethod.POST)],
                        consumes = [MediaType.APPLICATION_FORM_URLENCODED_VALUE])
        fun myEndpoint(@RequestParam body: Map<String,String>): String {
    
            return //...
        }
    

    (另请注意,我删除了 arrayOf 调用以支持数组文字,这些文字可用于 Kotlin 1.2 的注释)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-24
      • 1970-01-01
      • 2019-12-26
      • 2014-03-30
      • 1970-01-01
      • 2018-03-24
      相关资源
      最近更新 更多