簡體   English   中英

在 Java 中解析 Content-Type 標頭而不驗證字符集

[英]Parsing a Content-Type header in Java without validating the charset

給定一個 HTTP 標頭,例如:

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: something

要進行解析,可以使用較低級別的解析類:

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);

或者,仍然可以使用Apache 的解析並捕獲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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM