ContentType { public static ContentType parse(String contentType) { ContentType type = CACHE.get(contentType); if (type != null) return type; String mediaType = contentType; Charset charset = null; int firstSemicolon = contentType.indexOf(';'); if (firstSemicolon > 0) { mediaType = contentType.substring(0, firstSemicolon); int charsetStartIndex = contentType.indexOf("charset=", firstSemicolon + 1); if (charsetStartIndex > 0) { int charsetEndIndex = contentType.indexOf(';', charsetStartIndex + 8); charset = parseCharset(contentType.substring(charsetStartIndex + 8, charsetEndIndex == -1 ? contentType.length() : charsetEndIndex)); } } return new ContentType(contentType, mediaType, charset); } private  ContentType(String contentType, String mediaType, Charset charset); static ContentType parse(String contentType); static ContentType create(String mediaType, Charset charset); Optional<Charset> charset(); @Override String toString(); static final ContentType TEXT_HTML; static final ContentType TEXT_CSS; static final ContentType TEXT_PLAIN; static final ContentType TEXT_XML; static final ContentType APPLICATION_JSON; static final ContentType APPLICATION_JAVASCRIPT; static final ContentType APPLICATION_FORM_URLENCODED; static final ContentType APPLICATION_OCTET_STREAM; static final ContentType IMAGE_PNG; final String mediaType; }
@Test void parse() { ContentType type = ContentType.parse("application/json; charset=utf-8"); assertThat(type.mediaType).isEqualTo("application/json"); assertThat(type.charset()).get().isEqualTo(StandardCharsets.UTF_8); type = ContentType.parse("application/javascript; charset=utf-8"); assertThat(type.mediaType).isEqualTo("application/javascript"); assertThat(type.charset()).get().isEqualTo(StandardCharsets.UTF_8); type = ContentType.parse("application/vnd.maxmind.com-country+json; charset=UTF-8; version=2.1"); assertThat(type.mediaType).isEqualTo("application/vnd.maxmind.com-country+json"); assertThat(type.charset()).get().isEqualTo(StandardCharsets.UTF_8); type = ContentType.parse("image/png"); assertThat(type.mediaType).isEqualTo("image/png"); assertThat(type.charset()).isNotPresent(); type = ContentType.parse("multipart/form-data; boundary=----WebKitFormBoundaryaANA7UQAvnwa2EkM"); assertThat(type.mediaType).isEqualTo("multipart/form-data"); assertThat(type.charset()).isNotPresent(); }