我正在構建和測驗一個簡單的 Spring Boot API REST 教程。我遇到了一個我試圖理解的問題。呼叫 POST 方法以創建和持久化新物體時,我收到 HTTP 406(不可接受)。
問題是物體是持久的,但對客戶端的回應不是預期的(在這種情況下是使用 URI 創建的 HTTP 201)。
Tutorial 和 TutorialDto 類具有完全相同的屬性。這是定義:
public class TutorialDto {
private long id;
private String title;
private String description;
private boolean published;
...
}
這是我在 @RestController 類中的 POST 方法:
@PostMapping("/tutorial")
public ResponseEntity.BodyBuilder createTutorial(@RequestBody final TutorialDto tutorialDto) {
final TutorialDto createdTutorial = tutorialService.add(tutorialDto);
return ResponseEntity.created(URI.create(String.format("tutorial/%d", createdTutorial.getId())));
}
這是創建物體的@Service 方法:
@Transactional
public TutorialDto add(final TutorialDto tutorialDto) {
final Tutorial createdTutorial = tutorialRepository.save(modelmapper.map(tutorialDto, Tutorial.class));
return Optional.of(modelmapper.map(createdTutorial, TutorialDto.class))
.orElseThrow(() -> new TutorialCreationException(
String.format("Tutorial: %s could not be created", tutorialDto.getTitle()))
);
}
這是請求正文:
{
"title": "tutorial",
"description": "This is the first created tutorial"
}
這是回應正文:
{
"timestamp": "2022-04-16T00:40:36.626 00:00",
"status": 406,
"error": "Not Acceptable",
"path": "/api/v1/tutorial"
}
在回傳“ResponseEntity.created”后,我在控制器方法結束時收到 HTTP 406 回應。
提前致謝。
uj5u.com熱心網友回復:
看起來您使用了錯誤的 ResponseEntity.BodyBuilder。這是一個例子
因此,您的控制器代碼應如下所示:
@PostMapping("/tutorial")
public ResponseEntity createTutorial(@RequestBody final TutorialDto tutorialDto) {
final TutorialDto createdTutorial = tutorialService.add(tutorialDto);
return ResponseEntity.created(URI.create(String.format("tutorial/%d", createdTutorial.getId()))).body(createdTutorial);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/461377.html
上一篇:從@Async函式呼叫中取回資料
