我正在使用URL.openConnection()
从服务器下载内容。服务器说
Content-Type: text/plain; charset=utf-8
但connection.getContentEncoding()
会返回null
。怎么了?
答案 0 :(得分:27)
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检索charset。我已经提供了一个如何执行此操作的示例代码....
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
}
答案 1 :(得分:8)
这是记录的行为,因为getContentEncoding()
方法被指定为返回Content-Encoding
HTTP标头的内容,但未在您的示例中设置。您可以使用getContentType()
方法并自行解析生成的String,或者可能需要更多advanced HTTP客户端库,例如来自Apache的HTTP客户端库。
答案 2 :(得分:5)
作为@Buhake Sindi答案的补充。如果您使用的是Guava,而不是手动解析,您可以这样做:
MediaType mediaType = MediaType.parse(httpConnection.getContentType());
Optional<Charset> typeCharset = mediaType.charset();