19

URL.openConnection()用来从服务器下载东西。服务员说

Content-Type: text/plain; charset=utf-8

connection.getContentEncoding()回报null。怎么了?

4

3 回答 3

28

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 检索字符集。我已经包含了一个关于如何做到这一点的示例代码......

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
}
于 2010-10-14T14:33:43.537 回答
8

这是记录在案的行为,因为该getContentEncoding()方法被指定为返回Content-EncodingHTTP 标头的内容,这在您的示例中未设置。您可以使用该getContentType()方法并自行解析生成的字符串,或者可能使用更高级的HTTP 客户端库,例如来自Apache的客户端库。

于 2010-10-14T14:35:35.747 回答
6

就像对@Buhake Sindi 答案的补充一样。如果您使用的是 Guava,则可以执行以下操作,而不是手动解析:

MediaType mediaType = MediaType.parse(httpConnection.getContentType());
Optional<Charset> typeCharset = mediaType.charset();
于 2014-05-18T18:57:27.163 回答