Returns the Charset from the given content-type. - Java Network

Java examples for Network:Http

Description

Returns the Charset from the given content-type.

Demo Code

/******************************************************************************* 
 * Copyright (c) 2008 Red Hat, Inc. /*from   w w w .j a  v  a 2s  .c om*/
 * Distributed under license by Red Hat, Inc. All rights reserved. 
 * This program is made available under the terms of the 
 * Eclipse Public License v1.0 which accompanies this distribution, 
 * and is available at http://www.eclipse.org/legal/epl-v10.html 
 * 
 * Contributors: 
 * Xavier Coulon - Initial API and implementation 
 ******************************************************************************/
//package com.java2s;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.StringTokenizer;

public class Main {
    /**
     * Returns the {@link Charset} from the given content-type.
     * 
     * @param contentType
     *            the given content type that may contain some ";charset=...".
     * @param defaultCharsetName
     *            the name of the default charset to return in case when the given
     *            contentType would be null or would not contain any specific
     *            charset. If this name cannot be resolved into a valid charset, then "UTF-8" is used.
     * @return the value of the "charset" token in the given contentType, or
     *         the given defaultCharsetName, or "UTF-8" as a last resort.
     */
    public static Charset getContentCharSet(final String contentType,
            final String defaultCharsetName) {
        if (contentType != null) {
            final StringTokenizer stk = new StringTokenizer(contentType,
                    ";");
            while (stk.hasMoreTokens()) {
                final String token = stk.nextToken().toLowerCase()
                        .replace(" ", "");
                if (token.startsWith("charset=")) {
                    final StringTokenizer tokenSplitter = new StringTokenizer(
                            token, "=");
                    tokenSplitter.nextToken(); // skip the 'charset' part as we already know it
                    final String value = tokenSplitter.hasMoreTokens() ? tokenSplitter
                            .nextToken() : null;
                    return Charset.forName(value.toUpperCase());
                }
            }
        }
        try {
            return Charset.forName(defaultCharsetName);
        } catch (UnsupportedCharsetException e) {
            return Charset.forName("UTF-8");
        }
    }
}

Related Tutorials