Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending custom Content-Type with ResponseEntity<Resource>

Tags:

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

However, 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?

like image 601
Nigel Avatar asked May 31 '11 02:05

Nigel


People also ask

What does ResponseEntity OK () do?

ResponseEntity represents the whole HTTP response: status code, headers, and body. As a result, we can use it to fully configure the HTTP response.

What is the return type of ResponseEntity?

A ResponseEntity is returned. We give ResponseEntity a custom status code, headers, and a body. With @ResponseBody , only the body is returned. The headers and status code are provided by Spring.

What is the difference between ResponseBody and ResponseEntity?

ResponseEntity<> is a generic class with a type parameter, you can specify what type of object to be serialized into the response body. @ResponseBody is an annotation, indicates that the return value of a method will be serialized into the body of the HTTP response.


2 Answers

Another proposition :

return ResponseEntity
                  .ok()
                  .contentType(MediaType.IMAGE_GIF)
                  .body(resource);
like image 134
Mouad EL Fakir Avatar answered Sep 20 '22 03:09

Mouad EL Fakir


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);
        }
like image 20
gouki Avatar answered Sep 19 '22 03:09

gouki