private String bomAwareToString()

in sdk/core/azure-core-http-httpurlconnection/src/main/java/com/azure/android/core/http/httpurlconnection/HttpUrlConnectionAsyncHttpClient.java [296:346]


        private String bomAwareToString(byte[] bytes, String contentType) {
            if (bytes == null) {
                return null;
            }

            if (bytes.length >= 3
                && bytes[0] == (byte) 0xEF
                && bytes[1] == (byte) 0xBB
                && bytes[2] == (byte) 0xBF) {
                return new String(bytes, 3, bytes.length - 3, Charset.forName("UTF-8"));
            } else if (bytes.length >= 4
                && bytes[0] == (byte) 0x00
                && bytes[1] == (byte) 0x00
                && bytes[2] == (byte) 0xFE
                && bytes[3] == (byte) 0xFF) {
                return new String(bytes, 4, bytes.length - 4, Charset.forName("UTF-32BE"));
            } else if (bytes.length >= 4
                && bytes[0] == (byte) 0xFF
                && bytes[1] == (byte) 0xFE
                && bytes[2] == (byte) 0x00
                && bytes[3] == (byte) 0x00) {
                return new String(bytes, 4, bytes.length - 4, Charset.forName("UTF-32LE"));
            } else if (bytes.length >= 2
                && bytes[0] == (byte) 0xFE
                && bytes[1] == (byte) 0xFF) {
                return new String(bytes, 2, bytes.length - 2, Charset.forName("UTF-16BE"));
            } else if (bytes.length >= 2
                && bytes[0] == (byte) 0xFF
                && bytes[1] == (byte) 0xFE) {
                return new String(bytes, 2, bytes.length - 2, Charset.forName("UTF-16LE"));
            } else {
                /*
                 * Attempt to retrieve the default charset from the 'Content-Encoding' header,
                 * if the value isn't present or invalid fallback to 'UTF-8' for the default charset.
                 */
                if (contentType != null && contentType.length() != 0) {
                    try {
                        Matcher charsetMatcher = CHARSET_PATTERN.matcher(contentType);
                        if (charsetMatcher.find()) {
                            return new String(bytes, Charset.forName(charsetMatcher.group(1)));
                        } else {
                            return new String(bytes, Charset.forName("UTF-8"));
                        }
                    } catch (IllegalCharsetNameException | UnsupportedCharsetException ex) {
                        return new String(bytes, Charset.forName("UTF-8"));
                    }
                } else {
                    return new String(bytes, Charset.forName("UTF-8"));
                }
            }
        }