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