内容类型'application/json;charset=UTF-8'不支持,当我尝试将 JSON 发送到 Spring 时



当我将JSON软件包从jQuery发送到Spring RestController时,我有很多错误:

在春季:

解决[org.springframework.web.httpmediatipenotsupportedexception:content类型'应用程序/json; charset; charset = utf-8'不支持]

在Chrome中:

发布http://localhost/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;
}

您使用错误的介体类型,即APPLICATION_FORM_URLENCODED_VALUE在REST CONTTROLLER中使用。在通过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
}
}

最新更新