【问题标题】:Error while posting data in spring boot using @RestController使用 @RestController 在 Spring Boot 中发布数据时出错
【发布时间】: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


【解决方案1】:

您的端点只接受application/json,但您发送text/plain

只需将 content-type: application/json 添加到您的 HTTP 请求标头即可。

【讨论】:

    【解决方案2】:

    尝试从以下位置更改行:

    @RequestMapping(value = "/students/{studentId}/courses", method = RequestMethod.POST,
                consumes = "application/json",
                produces = {"application/json"})
    

    收件人:

    @RequestMapping(value = "/students/{studentId}/courses", method = RequestMethod.POST, consumes = MediaType.ALL_VALUE)
    

    【讨论】:

      猜你喜欢
      • 2017-10-15
      • 2021-05-20
      • 2015-07-30
      • 2022-10-23
      • 2018-08-07
      • 2020-08-07
      • 2017-10-30
      • 2023-03-09
      • 2021-10-13
      相关资源
      最近更新 更多