我使用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