MediaType { public static MediaType parse(String string) { Matcher typeSubtype = TYPE_SUBTYPE.matcher(string); if (!typeSubtype.lookingAt()) return null; String type = typeSubtype.group(1).toLowerCase(Locale.US); String subtype = typeSubtype.group(2).toLowerCase(Locale.US); String charset = null; Matcher parameter = PARAMETER.matcher(string); for (int s = typeSubtype.end(); s < string.length(); s = parameter.end()) { parameter.region(s, string.length()); if (!parameter.lookingAt()) return null; String name = parameter.group(1); if (name == null || !name.equalsIgnoreCase("charset")) continue; String charsetParameter = parameter.group(2) != null ? parameter.group(2) : parameter.group(3); if (charset != null && !charsetParameter.equalsIgnoreCase(charset)) { throw new IllegalArgumentException("Multiple different charsets: " + string); } charset = charsetParameter; } return new MediaType(string, type, subtype, charset); } private  MediaType(String mediaType, String type, String subtype, String charset); static MediaType parse(String string); String type(); String subtype(); Charset charset(); Charset charset(Charset defaultValue); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode();  }
@Test public void testParse() throws Exception { MediaType mediaType = MediaType.parse("text/plain;boundary=foo;charset=utf-8"); assertEquals("text", mediaType.type()); assertEquals("plain", mediaType.subtype()); assertEquals("UTF-8", mediaType.charset().name()); assertEquals("text/plain;boundary=foo;charset=utf-8", mediaType.toString()); assertTrue(mediaType.equals(MediaType.parse("text/plain;boundary=foo;charset=utf-8"))); assertEquals(mediaType.hashCode(), MediaType.parse("text/plain;boundary=foo;charset=utf-8").hashCode()); }
@Test public void testMultipleCharsets() { try { MediaType.parse("text/plain; charset=utf-8; charset=utf-16"); fail(); } catch (IllegalArgumentException expected) { } }