首页 > 解决方案 > Spring 无法正确解码 form-urlencoded 值

问题描述

我已经阅读了这个答案,因为我的问题与问题相似,但现在我被卡住了。
通过邮递员,我以这种方式发送数据:

在此处输入图像描述

在春天我像这样检索它们:

@PostMapping(path = PathConstants.START_ACTION, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public ResponseEntity<BaseResponse<ProcessInstance>> start(@PathVariable String processDefinitionId,
            @RequestParam("username") String params) {

这是它的工作,我可以打印用户名的值:

System.out.println("Username " + params);

问题是我需要发送的所有参数,但我无法将它们作为字符串或任何其他对象获取,因为我将发出许多不同的请求,而且并非所有请求都有“用户名”字段,并且顺便说一句,我需要收集所有这些。
我怎样才能做到这一点?我试过做

 @PostMapping(path = PathConstants.START_ACTION, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public ResponseEntity<BaseResponse<ProcessInstance>> start(@PathVariable String processDefinitionId,
            @RequestParam String params) {

或者

@PostMapping(path = PathConstants.START_ACTION, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public ResponseEntity<BaseResponse<ProcessInstance>> start(@PathVariable String processDefinitionId,
             String params) {

正如其他答案中所建议的那样,但在这些情况下 params 为空。什么是正确的工作方式?

标签: javaspringrestspring-booturlencode

解决方案


您需要@RequestBody方法中的注释,我建议使用MultiValueMap

@PostMapping(path = PathConstants.START_ACTION, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<BaseResponse<ProcessInstance>> start(@PathVariable String processDefinitionId, @RequestBody MultiValueMap<String, String> params)

推荐阅读