/** * Returns a media-type for. This would be the equivalent of the media type {@code "{primaryType}/{subType}"}. * * @param primaryType the left part of the represented type. * @param subType the right part of the represented type. * @return {@link MediaType} instance for given parameters. */ public static MediaType create(String primaryType, String subType) { return new MediaType(primaryType, subType, emptyMap(), null); }
/** * Returns a media-type for the given parameters. This would be the equivalent of the media type * {@code "{primaryType}/{subType}[; charset={charset}]"}. * * @param primaryType the left part of the represented type. * @param subType the right part of the represented type. * @param charset the value of the {@code charset} parameter. * @return {@link MediaType} instance for given parameters. */ public static MediaType create(String primaryType, String subType, Charset charset) { return new MediaType(primaryType, subType, emptyMap(), charset); }
/** * Creates a new {@link MediaType} instance keeping the {@code type} and {@code sub-type} but replacing the * {@code charset} with the value passed. * * @param charset the new charset to use or {@code null} to clear the current {@code charset}. * @return new immutable {@link MediaType} instance. */ public MediaType withCharset(Charset charset) { return new MediaType(this.getPrimaryType(), this.getSubType(), params, charset); }
/** * Parses a media type from its string representation. * * @param mediaType String representation to be parsed * @throws IllegalArgumentException if the {@code mimeType} cannot be parsed. * @return {@link MediaType} instance for the parsed {@code mediaType} string. */ public static MediaType parse(String mediaType) { try { MimeType mimeType = new MimeType(mediaType); String charsetParam = mimeType.getParameter(CHARSET_PARAM); Charset charset = isNotEmpty(charsetParam) ? Charset.forName(charsetParam) : null; Map<String, String> params = new HashMap<>(); for (String paramName : (List<String>) list(mimeType.getParameters().getNames())) { if (!CHARSET_PARAM.equals(paramName)) { params.put(paramName, mimeType.getParameter(paramName)); } } return new MediaType(mimeType.getPrimaryType(), mimeType.getSubType(), params, charset); } catch (MimeTypeParseException e) { throw new IllegalArgumentException("MediaType cannot be parsed: " + mediaType, e); } }