繁体   English   中英

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

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

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

在春天:

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

在 Chrome 中:

POST 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用于在休息控制器中使用。 在传递 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
}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM