~/ learn/ comp-348/ cards/ Headers, charsets, and HttpURLConnection
1 of 5

Derive the charset from the server's Content-Type header

Derive the charset from the server's Content-Type header

Answer

String type = conn.getContentType(); Charset cs = StandardCharsets.UTF_8; int i = (type == null) ? -1 : type.indexOf("charset="); if (i != -1) cs = Charset.forName(type.substring(i + 8).trim());

Default first, then override only if the parameter is present — the null-safe order. The 8 is the length of "charset="; Charset.forName throws UnsupportedCharsetException for a name this JVM does not know, so a hostile server cannot be trusted blindly.

Harold 4e ch7 §Reading the Header; §Configuring the Connection; §HttpURLConnection

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/7f293e7c-f192-45f0-9ccb-fb8987cedb12/flashcard utf-8 LF