开发者

Sending custom Content-Type with ResponseEntity<Resource>

开发者 https://www.devze.com 2023-03-09 15:34 出处:网络
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:

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:

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

H开发者_StackOverflow中文版owever, the return type is being overridden to text/html in ResourceHttpMessageConverter.

Other than implementing my own HttpMessageConverter and injecting this into the AnnotationMethodHandlerAdapter, is there any way for me to force the Content-Type?


Another proposition :

return ResponseEntity
                  .ok()
                  .contentType(MediaType.IMAGE_GIF)
                  .body(resource);


try injecting the HttpServletResponse object and force the content type from there.

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


This should be the approach to set all the parameters like httpStatus , contentType and body

ResponseEntity.status(status).contentType(MediaType.APPLICATION_JSON).body(response);

This sample is using the ResponseEntity.BodyBuilder interface.


Those two approaches are correct. You can also use ResponseEntity<?> at top so you can send multiple types of data.

0

精彩评论

暂无评论...
验证码 换一张
取 消