ams
ams

Reputation: 62762

How parse an http accept header in spring?

I want to parse an HTTP accept header in Spring to determine if I can send back JSON. I am trying with the following code.

class MediaTypeUtil {
  private final static Logger logger = LoggerFactory.getLogger(MediaTypeUtil.class);
  static boolean acceptsJson(HttpServletRequest request) {
    try {
      String accept = request.getHeader("Accept");
      MediaType requestType = MediaType.valueOf(accept);
      return MediaType.APPLICATION_JSON.isCompatibleWith(requestType);
    } catch (InvalidMediaTypeException e) {
      logger.debug("MediaType parsing error",e);
      return false;
    }
  }
}

When a request arrives with accept header value of application/json, application/javascript, text/javascript, text/json I end up with an exception

Caused by: org.springframework.util.InvalidMimeTypeException: Invalid mime type "application/json, application/javascript, text/javascript, text/json": Invalid token character ',' in token "json, application/javascript, text/javascript, text/json"
    at org.springframework.util.MimeTypeUtils.parseMimeTypeInternal(MimeTypeUtils.java:262)

This code is being used from a Servlet Filter so I can't rely on SpringMVC annotations.

Does Spring has a method for parsing accept header and determining if it is compatible with a specific media type?

Upvotes: 3

Views: 2669

Answers (1)

Marco Behler
Marco Behler

Reputation: 3724

Spring itself does it exactly like you internally (i.e. getting the ACCEPT header from the request), but they feed it to this call:

MediaType.parseMediaTypes(get(ACCEPT));

Which will return you a List<MediaType> that you need to work with.

Upvotes: 7

Related Questions