[英]URLConnection does not get the charset
我正在使用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檢索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
}
正如@Buhake Sindi的回答一樣。 如果您使用的是Guava,而不是手動解析,您可以執行以下操作:
MediaType mediaType = MediaType.parse(httpConnection.getContentType());
Optional<Charset> typeCharset = mediaType.charset();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.