Extracts only the mime-type from a Content-Type HTTP header. - Java Network

Java examples for Network:Http

Description

Extracts only the mime-type from a Content-Type HTTP header.

Demo Code

/*/*from w  w w  .  ja v a2s  .  c o  m*/
 * Copyright 2001-2013 Geert Bevin (gbevin[remove] at uwyn dot com)
 * Licensed under the Apache License, Version 2.0 (the "License")
 */
import javax.net.ssl.*;
import javax.servlet.http.Cookie;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

public class Main{
    public static final String CHARSET = "charset=";
    /**
     * Extracts only the mime-type from a Content-Type HTTP header. Thus a header
     * like this: <code>text/html;charset=UTF-8</code> will return: <code>text/html</code>
     *
     * @param contentType the Content-Type header
     * @return the content type header without the charset
     * @since 1.6
     */
    public static String extractMimeTypeFromContentType(String contentType) {
        int charset_index = contentType.indexOf(CHARSET);
        if (charset_index != -1) {
            char indexed_char;
            do {
                indexed_char = contentType.charAt(--charset_index);
            } while (' ' == indexed_char);

            if (';' == indexed_char) {
                return contentType.substring(0, charset_index);
            }
        }

        return contentType;
    }
}

Related Tutorials