我URL.openConnection()
用来从服务器下载东西。服务员说
Content-Type: text/plain; charset=utf-8
但connection.getContentEncoding()
回报null
。怎么了?
我URL.openConnection()
用来从服务器下载东西。服务员说
Content-Type: text/plain; charset=utf-8
但connection.getContentEncoding()
回报null
。怎么了?
从URLConnection.getContentEncoding()
返回的值返回来自标头的值Content-Encoding
代码来自URLConnection.getContentEncoding()
/**
* Returns the value of the <code>content-encoding</code> header field.
*
* @return the content encoding of the resource that the URL references,
* or <code>null</code> if not known.
* @see java.net.URLConnection#getHeaderField(java.lang.String)
*/
public String getContentEncoding() {
return getHeaderField("content-encoding");
}
相反,而是执行connection.getContentType()
检索 Content-Type 并从 Content-Type 检索字符集。我已经包含了一个关于如何做到这一点的示例代码......
String contentType = connection.getContentType();
String[] values = contentType.split(";"); // values.length should be 2
String charset = "";
for (String value : values) {
value = value.trim();
if (value.toLowerCase().startsWith("charset=")) {
charset = value.substring("charset=".length());
}
}
if ("".equals(charset)) {
charset = "UTF-8"; //Assumption
}
就像对@Buhake Sindi 答案的补充一样。如果您使用的是 Guava,则可以执行以下操作,而不是手动解析:
MediaType mediaType = MediaType.parse(httpConnection.getContentType());
Optional<Charset> typeCharset = mediaType.charset();