我使用URL.openConnection()
从服务器下载某些东西。服务器说URLConnection没有得到字符集
Content-Type: text/plain; charset=utf-8
但connection.getContentEncoding()
回报null
。怎么了?
我使用URL.openConnection()
从服务器下载某些东西。服务器说URLConnection没有得到字符集
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和检索的内容类型的字符集。我将在如何做到这一点的样本代码....
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的答案一样。如果使用的是番石榴,而不是手动解析你可以这样做:
MediaType mediaType = MediaType.parse(httpConnection.getContentType());
Optional<Charset> typeCharset = mediaType.charset();
此相关的线程可以帮助其他人:http://stackoverflow.com/questions/9112259/obtaining-response-charset-of-response to-get-or-post-request – Spoonface 2012-12-23 10:39:29
此外还有一个很好的原因connection.getContentEncoding()返回null:它返回http头的“Content-encoding”字段,**不是**应该给你一个字符集。例如,如果收到的数据是压缩的,那么应该使用它,并为您提供了转换数据的方式,以便您可以读取它。 https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 – jdarthenay 2016-03-14 06:25:13