Bar*_*lom 19 java content-type http urlconnection httpurlconnection
我正在使用URL.openConnection()从服务器下载的东西.服务器说
Content-Type: text/plain; charset=utf-8
Run Code Online (Sandbox Code Playgroud)
但connection.getContentEncoding()回报null.怎么了?
Buh*_*ndi 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");
}
Run Code Online (Sandbox Code Playgroud)
相反,而是做一个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
}
Run Code Online (Sandbox Code Playgroud)
小智 5
正如@Buhake Sindi的回答一样.如果您使用的是Guava,而不是手动解析,您可以执行以下操作:
MediaType mediaType = MediaType.parse(httpConnection.getContentType());
Optional<Charset> typeCharset = mediaType.charset();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16413 次 |
| 最近记录: |