Java Charset Create getCharsetFromContentType(String contentType)

Here you can find the source of getCharsetFromContentType(String contentType)

Description

get Charset From Content Type

License

Apache License

Declaration

public static String getCharsetFromContentType(String contentType) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;

import java.util.Locale;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    private static final Pattern charsetPattern = Pattern.compile("(?i)\\bcharset=\\s*(?:\"|')?([^\\s,;\"']*)");

    public static String getCharsetFromContentType(String contentType) {
        if (contentType == null) {
            return null;
        }//from  w  ww  .j  a  v a  2 s.c o  m
        Matcher m = charsetPattern.matcher(contentType);
        if (m.find()) {
            String charset = m.group(1).trim();
            charset = charset.replace("charset=", "");
            if (charset.isEmpty())
                return null;
            try {
                if (Charset.isSupported(charset))
                    return charset;
                charset = charset.toUpperCase(Locale.ENGLISH);
                if (Charset.isSupported(charset))
                    return charset;
            } catch (IllegalCharsetNameException e) {
                // if our advanced charset matching fails.... we just take the
                // default
                return null;
            }
        }
        return null;
    }
}

Related

  1. getCharset(String encoding)
  2. getCharset(String name)
  3. getCharsetForSortOrder(final int sortOrder)
  4. getCharsetFromContent(URL url)
  5. getCharsetFromContentType(String contentType)
  6. getCharsetFromContentTypeString(String contentType)
  7. getCharsetList(List availableCharsets, Charset actualCharset)
  8. getCharsetName(String location)
  9. getCharsetOrDefault(String charsetName)