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

标签 java mime-types

给定一个 HTTP header ,例如:

Content-Type: text/plain; charset=something

我想使用完全符合 RFC 的解析来提取 MIME 类型和字符集,但不“验证”字符集。通过验证,我的意思是我不想使用 Java 的内部字符集机制,以防 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:某事

最佳答案

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

import org.apache.http.entity.ContentType;

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

String charsetName;
String mimeType;

try {
  ContentType contentType = ContentType.parse(header); // here exception may be thrown
   mimeType = contentType.getMimeType();
   Charset charset = contentType.getCharset();
   charsetName = charset != null ? charset.name() : null;
} catch( UnsupportedCharsetException e) {
    charsetName = e.getCharsetName(); // extract unsupported charsetName
    mimeType = header.substring(0, header.indexOf(';')); // in case of exception, mimeType needs to be parsed separately
}

缺点是,在出现 UnsupportedCharsetException 的情况下,还需要以不同的方式提取 mimeType

关于java - 在 Java 中解析 Content-Type header 而不验证字符集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59237625/

相关文章:

javascript - Express:在 304 Not Modified 上发送 Content-Type

iis - 从 IE 下载 Docx - 在 IIS 中设置 MIME 类型

google-chrome - 如何在 Ubuntu 中向 firefox 和 chrome 添加新的 MIME/协议(protocol)处理程序?

java - 在Java中以编程方式设置gmail中不太安全的应用程序

java - 使用jade(pug)创建jsp

java - 单击按钮时显示/隐藏 ImageView

java - 在 Java 中读取 OpenSSL 生成的 PEM/DER 格式的 S/MIME 消息

grails - Grails更改了request.format?

http - .ts 文件始终被识别为 text/vnd.trolltech.linguist 而不会被识别为 video/mp2t

java - 安卓蓝牙配对: How to make sure to get bluetooth pairing request in the front dialog instead of a notification?