Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap

匿名 (未验证) 提交于 2019-12-03 03:06:01

问题:

Based on the answer for problem with x-www-form-urlencoded with Spring @Controller

I have written the below @Controller method

@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");             }     } 

the request to which fails with the below error

{   "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 was far more friendly, but couldn't use it now given the practical restrictions here]

回答1:

The problem is that when we use application/x-www-form-urlencoded, Spring doesn't understand it as a RequestBody. So, if we want to use this we must remove the @RequestBody annotation.

Then try the following:

@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; } 

Note that removed the annotation @RequestBody

answer: Http Post request with content type application/x-www-form-urlencoded not working in Spring



回答2:

It seems that now you can just mark the method parameter with @RequestParam and it will do the job for you.

@PostMapping( "some/request/path" ) public void someControllerMethod( @RequestParam Map body ) {   //work with Map } 


回答3:

Add a header to your request to set content type to application/json

curl -H 'Content-Type: application/json' -s -XPOST http://your.domain.com/ -d YOUR_JSON_BODY 

this way spring knows how to parse the content.



回答4:

My solution with Alamofire on swift 3

Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON  


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!