Java Charset Create getCharsetFromContentType(String contentType)

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

Description

Parse out a charset from a content type header.

License

LGPL

Parameter

Parameter Description
contentType e.g. "text/html; charset=EUC-JP"

Return

"EUC-JP", or null if not found. Charset is trimmed and uppercased.

Declaration

static String getCharsetFromContentType(String contentType) 

Method Source Code

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

import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Locale;

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

    /**/*from w  ww.j a  v a2  s  . c o m*/
     * Parse out a charset from a content type header. If the charset is not supported, returns null (so the default
     * will kick in.)
     * @param contentType e.g. "text/html; charset=EUC-JP"
     * @return "EUC-JP", or null if not found. Charset is trimmed and uppercased.
     */
    static String getCharsetFromContentType(String contentType) {
        if (contentType == null)
            return null;
        Matcher m = charsetPattern.matcher(contentType);
        if (m.find()) {
            String charset = m.group(1).trim();
            if (Charset.isSupported(charset))
                return charset;
            charset = charset.toUpperCase(Locale.ENGLISH);
            if (Charset.isSupported(charset))
                return charset;
        }
        return null;
    }
}

Related

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