【发布时间】:2020-09-27 02:37:41
【问题描述】:
我在使用 REST API 编写 Spring Boot 应用程序时不断收到此错误。
{ “状态”:415, "error": "不支持的媒体类型", "message": "不支持内容类型'text/plain'" }
如何消除错误?
我的Post Request代码如下,在我的
StudentController.java,
@RequestMapping(value = "/students/{studentId}/courses", method = RequestMethod.POST,
consumes = "application/json",
produces = {"application/json"})
public ResponseEntity<Void> registerStudentForCourse(@PathVariable String studentId, @RequestBody course newCourse)
{
course course1 = studentService.addCourse(studentId, newCourse);
if (course1 == null)
return ResponseEntity.noContent().build();
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(course1.getId()).toUri();
return ResponseEntity.created(location).build();
}
我对 requestBody 的邮递员输入如下,为 student 添加新课程。代码在json中
{
"name":"Microservices",
"description"="10 Steps",
"steps":
[
"Learn How to Break Things up ",
"Automate the hell out of everything ",
"Have fun"
]
}
My addcourse()方法如下:
SecureRandom random = new SecureRandom();
public course addCourse(String studentId, course cour)
{
Student student = retrieveStudent(studentId);
if(student==null)
{
return null;
}
String randomId = new BigInteger(130,random).toString(32);
cour.setId(randomId);
student.getCourses().add(cour);
return cour;
}
【问题讨论】:
-
这个异常告诉你一切......你发送的是纯文本,而不是 JSON(根据内容类型)。所以修复你的邮递员请求。
-
你也有魔法字符串(而不是
MediaType.APPLICATION_JSON_VALUE),除了@PostMapping("/students/{studentId}/courses")之外的一切都只是分散注意力。
标签: java spring-boot rest