问题描述
当我将 JSON 包从 jQuery 发送到 Spring RestController 时,我有很多错误:
在春天:
已解决 [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported]
在 Chrome 中:
POST 415
(匿名)@main.js:11
我的jQuery代码:
$(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
});
});
});
我的 Spring RestController 代码:
@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
}
}
实体用户:
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String name;
private int age;
}
1楼
您正在使用错误的媒体类型,即APPLICATION_FORM_URLENCODED_VALUE
用于在休息控制器中使用。
在传递 json 请求时使用MediaType.APPLICATION_JSON_UTF8_VALUE
。
@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
}
}