Inexactly Comparing MediaTypes with Spring

Featured image for sharing metadata for article

When we're interacting with a HttpServletRequest and we want to do something based on the Accept / Content-Type header, for instance within a HandlerMethodArgumentResolver, we would lean on Spring's MediaType class to parse the string value.

But the issue is that this doesn't always work for what we want it to.

For instance, if you're expecting application/json, but receive a request with application/json;charset=UTF-8 or application/json;v=1 will not match.

Update 2021-01-11: Although the below may be helpful, it is unnecessary as MediaType provides the isCompatibleWith method for this exact reason!

The solution I've used is the below, to provide us a straightforward way to ignore parameters from the equality check:

private boolean compareMediaType(MediaType lhs, MediaType rhs) {
  if (null == lhs || null == rhs) {
    return false;

  return lhs.getType().equals(rhs.getType()) && lhs.getSubtype().equals(rhs.getSubtype());

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #spring #java.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.