集册 Java实例教程 从内容类型标头解析出字符集。

从内容类型标头解析出字符集。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

516
从内容类型标头解析出字符集。
/** from 
时代Java - nowjava.com**/


//package com.nowjava;


import java.nio.charset.Charset;

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;\"/]*)/?>");


    /**

     * 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.

     */

    public static String getCharsetFromContentType(String contentType) {

        if (contentType == null)

            return null;

        Matcher m = charsetPattern.matcher(contentType);

        if (m.find()) {
        /*
        N o  w  J a v a . c o m - 时  代  Java 提 供
        */

            String charset = m.group(1).trim();

            if (Charset.isSupported(charset))

                
展开阅读全文