0

I have this piece of code:

@RequestMapping(value = "/test", produces = "text/plain")
@ResponseBody
public Object test() {
    return "true";
}

And what I want is returning in this case "true" with 'text/plain' type even when my accept header says 'application/json' or anything else. Now I get 406 when I do that. Is there simple way to do such a thing? I mean really simple? I'd rather not change my config files that will affect more than just this one method.

EDIT: I found partial solution

@RequestMapping(value = "/test")
@ResponseBody
public Object test(){
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.TEXT_PLAIN);
    return new ResponseEntity<>("true", responseHeaders, HttpStatus.OK);
}

But is there anyone who knows simpler, shorter solution?

2 Answers2

0

For a more flexible setting you can remove produces = "text/plain" and maybe add headers ="Accept=application/json". see Baeldung article:

Mapping media types produced by a controller method is worth special attention – we can map a request based on its Accept header via the @RequestMapping headers attribute introduced above:

@RequestMapping(
  value = "/ex/foos", 
  method = GET, 
  headers = "Accept=application/json")
@ResponseBody
public String getFoosAsJsonFromBrowser() {
    return "Get some Foos with Header Old";
}

The matching for this way of defining the Accept header is flexible – it uses contains instead of equals, so a request such as the following would still map correctly:

curl -H "Accept:application/json,text/html"  http://localhost:8080/spring-rest/ex/foos
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
0

Declare header in caller

accept:text/plain

So that you declare that response from server as text/plain

Here caller can be (postman, JS etc)

Tarun
  • 986
  • 6
  • 19