一尘不染

@RequestBody MultiValueMap不支持内容类型'application / x-www-form-urlencoded; charset= UTF-8'

spring-mvc

基于Spring @Controller对x-www-form-urlencoded的问的答案

我写了下面的@Controller方法

@RequestMapping(value = "/{email}/authenticate", method = RequestMethod.POST
            , produces = {"application/json", "application/xml"}
            ,  consumes = {"application/x-www-form-urlencoded"}
    )
     public
        @ResponseBody
        Representation authenticate(@PathVariable("email") String anEmailAddress,
                                    @RequestBody MultiValueMap paramMap)
                throws Exception {


            if(paramMap == null || paramMap.get("password") == null) {
                throw new IllegalArgumentException("Password not provided");
            }
    }

失败的请求因以下错误

{
  "timestamp": 1447911866786,
  "status": 415,
  "error": "Unsupported Media Type",
  "exception": "org.springframework.web.HttpMediaTypeNotSupportedException",
  "message": "Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported",
  "path": "/users/usermail%40gmail.com/authenticate"
}

[PS:Jersey要友好得多,但鉴于这里的实际限制,现在无法使用它]


阅读 606

收藏
2020-06-01

共1个答案

一尘不染

问题在于,当我们使用 application / x-www-form-urlencoded时
,Spring不会将其理解为RequestBody。因此,如果要使用它,则必须删除 @RequestBody 批注。

然后尝试以下操作:

@RequestMapping(value = "/{email}/authenticate", method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, 
        produces = {MediaType.APPLICATION_ATOM_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public @ResponseBody  Representation authenticate(@PathVariable("email") String anEmailAddress, MultiValueMap paramMap) throws Exception {
   if(paramMap == null && paramMap.get("password") == null) {
        throw new IllegalArgumentException("Password not provided");
    }
    return null;
}

请注意,删除了注释 @RequestBody

2020-06-01