我使用 Spring Boot 和基于 @ResponseBody 的方法,如下所示:
@RequestMapping(value = VIDEO_DATA_PATH, method = RequestMethod.GET)
public @ResponseBody Response getData(@PathVariable(ID_PARAMETER) long id, HttpServletResponse res) {
Video video = null;
Response response = null;
video = videos.get(id - 1);
if (video == null) {
// TODO how to return 404 status
}
serveSomeVideo(video, res);
VideoSvcApi client = new RestAdapter.Builder()
.setEndpoint("http://localhost:8080").build().create(VideoSvcApi.class);
response = client.getData(video.getId());
return response;
}
public void serveSomeVideo(Video v, HttpServletResponse response) throws IOException {
if (videoDataMgr == null) {
videoDataMgr = VideoFileManager.get();
}
response.addHeader("Content-Type", v.getContentType());
videoDataMgr.copyVideoData(v, response.getOutputStream());
response.setStatus(200);
response.addHeader("Content-Type", v.getContentType());
}
我尝试了一些典型的方法:
res.setStatus(HttpStatus.NOT_FOUND.value());
新的 ResponseEntity(HttpStatus.BAD_REQUEST);
但我需要返回Response http://square.github.io/retrofit/javadoc/retrofit/client/Response.html.
如果视频为空,如何在此处返回 404 状态代码?
这很简单,通过抛出org.springframework.web.server.ResponseStatusException
:
throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "entity not found"
);
它兼容@ResponseBody
并具有任何返回值。需要 Spring 5+
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)