在Java中解析Content-Type头而不验证字符集

问题描述 投票:0回答:2

给出一个HTTP标头,如:

Content-Type: text/plain; charset=something

我想使用完全符合RFC的解析来提取MIME类型和字符集,但不“验证”字符集。通过验证,我的意思是我不想使用Java的内部Charset机制,以防Java不知道该字符集(但对于其他应用程序仍然有意义)。以下代码不起作用,因为它执行此验证:

import org.apache.http.entity.ContentType;

String header = "text/plain; charset=something";

ContentType contentType = ContentType.parse(header);
Charset contentTypeCharset = contentType.getCharset();

System.out.println(contentType.getMimeType());
System.out.println(contentTypeCharset == null ? null : contentTypeCharset.toString());

此抛出java.nio.charset.UnsupportedCharsetException: something

java mime-types
2个回答
0
投票

要进行解析,可以使用较低级别的解析类:

import org.apache.http.HeaderElement;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicHeaderValueParser;

String header = "text/plain; charset=something";

HeaderElement headerElement = BasicHeaderValueParser.parseHeaderElement(header, null);
String mimeType = headerElement.getName();
String charset = null;
for (NameValuePair param : headerElement.getParameters()) {
    if (param.getName().equalsIgnoreCase("charset")) {
        String s = param.getValue();
        if (!StringUtils.isBlank(s)) {
            charset = s;
        }
        break;
    }
}

System.out.println(mimeType);
System.out.println(charset);

0
投票

或者,仍然可以使用Apache's parse并使用UnsupportedCharsetException捕获getCharsetName()提取名称

import org.apache.http.entity.ContentType;

String header = "text/plain; charset=something";

String charsetName;
String mime type;

try {
  // Call throwing operation here

} catch( UnsupportedCharsetException e) {
    charsetName = e.getCharsetName(); // extract unsupported charsetName
}

© www.soinside.com 2019 - 2024. All rights reserved.