簡體   English   中英

使用 @RestController 在 spring 引導中發布數據時出錯

[英]Error while posting data in spring boot using @RestController

在使用 REST API 編寫 spring 引導應用程序時,我不斷收到此錯誤。

{ "status": 415, "error": "Unsupported Media Type", "message": "Content type 'text/plain' not supported" }

如何擺脫錯誤?

我的 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 的 postman 輸入如下,為學生添加新課程。 代碼在 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;
}

您的端點只接受application/json但您發送text/plain

只需將content-type: application/json添加到您的 HTTP 請求 header 中。

嘗試從以下位置更改線路:

@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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM