当前位置: 首页 > 知识库问答 >
问题:

内容类型'应用程序/json; charset=UTF-8'不支持,当我尝试发送JSON到Spring

郎仰岳
2023-03-14

当我从jQuery向Spring RestController发送JSON包时,我有很多错误:

在Spring:

已解决[org.springframework.web.HttpMediaTypeNotSupportedException:内容类型'application/json;字符集=UTF-8'不受支持]

在Chrome:

邮政http://localhost/post415

(匿名)@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个答案

周志文
2023-03-14

您使用了错误的mediatype,即APPLICATION_FORM_URLENCODED_VALUE用于在Rest控制器中消费。当您传递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
}

}
 类似资料: