Content type 'application/json;charset=UTF-8' not supported, when i try send JSON to Spring

问题: When i send JSON package from jQuery to Spring RestController i have many errors: In Spring: Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: C...

问题:

When i send JSON package from jQuery to Spring RestController i have many errors:

In Spring:

Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported]

in Chrome:

POST http://localhost/post 415

(anonymous) @ main.js:11

My jQuery code:

$(document).ready(function() {

$('#go').on('click', function() {

    var user = {
        "name" : "Tom",
        "age" : 23
    };

    $.ajax({
        type: 'POST',
        url: "http://localhost/post",
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(user),
        dataType: 'json',
        async: true
    });

   });

 });

My Spring RestController code:

@RestController
public class mainController {
@RequestMapping(value = "/post", method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
        produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public ResponseEntity<Object> postUser(@RequestBody User user){
System.out.println(user);
return new ResponseEntity<>("Success", HttpStatus.OK);
}

@RequestMapping(value = "/get", method = RequestMethod.GET)
public User getStr(){
    System.out.println("-------------------------");
    return new User("Tom", 56); //'Get' Check
}

}

Entity User:

@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class User {
  private String name;
  private int age;
}

回答1:

you are using wrong mediatype i.e APPLICATION_FORM_URLENCODED_VALUE for consume in rest conttroller. Use MediaType.APPLICATION_JSON_UTF8_VALUE as you are passing json request.

@RestController
public class mainController {
@RequestMapping(value = "/post", method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_JSON,
        produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public ResponseEntity<Object> postUser(@RequestBody User user){
System.out.println(user);
return new ResponseEntity<>("Success", HttpStatus.OK);
}

@RequestMapping(value = "/get", method = RequestMethod.GET)
public User getStr(){
    System.out.println("-------------------------");
    return new User("Tom", 56); //'Get' Check
}

}
  • 发表于 2019-02-24 11:34
  • 阅读 ( 4408 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除