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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With