Search code examples
springrequest-mappingget-mapping

GetMapping "produces" works even though doesn't match accept header


Intro

There is a @GetMapping attribute, as the following in one of our projects:

@GetMapping(path = "/", produces = SaConstants.SA_MEDIA_TYPE)
public HttpEntity<Resource<Home>> get(HttpServletResponse response) {

In the SaConstants class:

public static final String SA_MEDIA_TYPE="application/sa+json";

When I access the page from any internet browser, I am getting the proper response that I want - and my breakpoint in the controller is being triggered.

The browser is sending the following headers:

Host: 127.0.0.1:8001
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
DNT: 1
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
Cookie: io=Qt74kp5V5ziUNIxlAAAG

When I make a request to the page, without an Accept header, the page is not working.

If I add to postman the following Accept header, everything works:

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 

Question

My question are:

  • why does it work even if the Accept: header of the request doesn't match the produces attribute of the Rest Controller?
  • Why does it fail if no Accept header is provided (given the first question).

Solution

  • "*/*" means all types, this header is by default provided by most of the popular browsers