/** * Creates a {@code MediaType} by parsing the specified string. The string must look like a standard MIME type * string, for example "text/html" or "application/xml". There can optionally be parameters present, for example * "text/html; encoding=UTF-8" or "application/xml; q=0.8". * * @param text A string representing a media type. * @return A {@code MediaType} object. * @throws java.lang.IllegalArgumentException If the string is not a valid media type string. */ public static MediaType fromString(String text) { Matcher matcher = MEDIA_TYPE_PATTERN.matcher(text); if (!matcher.matches()) { throw new IllegalArgumentException("Invalid media type string: " + text); } String type; String subType; if (matcher.group(GROUP_INDEX) != null) { type = matcher.group(GROUP_INDEX); subType = matcher.group(GROUP_INDEX); } else { type = matcher.group(TYPE_INDEX); subType = matcher.group(SUBTYPE_INDEX); } Map<String, String> parametersBuilder = new HashMap<>(); Matcher parametersMatcher = PARAMETER_PATTERN.matcher(matcher.group(GROUP_MATCHER_INDEX)); while (parametersMatcher.find()) { parametersBuilder.put(parametersMatcher.group(1), parametersMatcher.group(2)); } return new MediaType(type, subType, Collections.unmodifiableMap(parametersBuilder)); }
/** * Creates a {@code MediaType} by parsing the specified string. The string must look like a standard MIME type * string, for example "text/html" or "application/xml". There can optionally be parameters present, for example * "text/html; encoding=UTF-8" or "application/xml; q=0.8". * * @param text A string representing a media type. * @return A {@code MediaType} object. * @throws java.lang.IllegalArgumentException If the string is not a valid media type string. */ public static MediaType fromString(String text) { Matcher matcher = MEDIA_TYPE_PATTERN.matcher(text); if (!matcher.matches()) { throw new IllegalArgumentException("Invalid media type string: " + text); } String type; String subType; if (matcher.group(GROUP_INDEX) != null) { type = matcher.group(GROUP_INDEX); subType = matcher.group(GROUP_INDEX); } else { type = matcher.group(TYPE_INDEX); subType = matcher.group(SUBTYPE_INDEX); } Map<String, String> parametersBuilder = new HashMap<>(); Matcher parametersMatcher = PARAMETER_PATTERN.matcher(matcher.group(GROUP_MATCHER_INDEX)); while (parametersMatcher.find()) { parametersBuilder.put(parametersMatcher.group(1), parametersMatcher.group(2)); } return new MediaType(type, subType, Collections.unmodifiableMap(parametersBuilder)); }