spring 使用 ResponseEntity<Resource> 发送自定义内容类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6182362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending custom Content-Type with ResponseEntity<Resource>
提问by Nigel
I am trying to use the ResponseEntity return type in my Spring WebMVC 3.0.5 controller. I am returning an image, so I want to set the Content Type to image/gif with the following code:
我正在尝试在 Spring WebMVC 3.0.5 控制器中使用 ResponseEntity 返回类型。我正在返回一个图像,因此我想使用以下代码将内容类型设置为 image/gif:
@RequestMapping(value="/*.gif")
public ResponseEntity<Resource> sendGif() throws FileNotFoundException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_GIF);
return new ResponseEntity<Resource>(ctx.getResource("/images/space.gif"), headers, HttpStatus.OK);
}
However, the return type is being overridden to text/html in ResourceHttpMessageConverter.
但是,返回类型在 ResourceHttpMessageConverter 中被覆盖为 text/html。
Other than implementing my own HttpMessageConverter and injecting this into the AnnotationMethodHandlerAdapter, is there any way for me to force the Content-Type?
除了实现我自己的 HttpMessageConverter 并将其注入 AnnotationMethodHandlerAdapter 之外,我还有什么方法可以强制使用 Content-Type?
回答by Mouad EL Fakir
Another proposition :
另一个提议:
return ResponseEntity
.ok()
.contentType(MediaType.IMAGE_GIF)
.body(resource);
回答by gouki
try injecting the HttpServletResponse object and force the content type from there.
尝试注入 HttpServletResponse 对象并从那里强制内容类型。
@RequestMapping(value="/*.gif")
public ResponseEntity<Resource> sendGif(final HttpServletResponse response) throws FileNotFoundException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_GIF);
response.setContentType("image/gif"); // set the content type
return new ResponseEntity<Resource>(ctx.getResource("/images/space.gif"), headers, HttpStatus.OK);
}
回答by Nandan
Those two approaches are correct. You can also use
ResponseEntity<?>at top so you can send multiple types of data.
这两种方法都是正确的。您还可以ResponseEntity<?>在顶部使用
,以便您可以发送多种类型的数据。
回答by Samrat
This should be the approach to set all the parameters like httpStatus , contentType and body
这应该是设置所有参数的方法,如 httpStatus 、 contentType 和 body
ResponseEntity.status(status).contentType(MediaType.APPLICATION_JSON).body(response);
ResponseEntity.status(status).contentType(MediaType.APPLICATION_JSON).body(response);
This sample is using the ResponseEntity.BodyBuilder interface.
此示例使用 ResponseEntity.BodyBuilder 接口。

