gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:14:28 24 4
gpt4 key购买 nike

给定一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com