Problem: content type always being set as “text/html”
The problem is when you set your method return type as string then spring by default uses StringHttpMessageConverter and thus sets the Content-type
header to text/plain
. If you want to return a JSON string yourself and set the header to application/json
, use a return type of ResponseEntity
and add appropriate headers to it.
@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json") public ResponseEntity < String > foo() {
final HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity < String > ("{\"message\": \"hello\"}", httpHeaders, HttpStatus.OK);
}
And if you are wondering why its content type not set to application/json even after you adding produces = “application/json”. Then thing you need to understand is that the RequestMapping#produces() element in
@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
serves only to restrict the mapping for your request handlers. It does nothing else.