URLConnection没有得到charset

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)


Wal*_*inz 8

这是记录的行为,因为getContentEncoding()指定了方法以返回Content-EncodingHTTP标头的内容,这在您的示例中未设置.您可以使用该getContentType()方法并自行解析生成的String,也可以使用Apache中高级的 HTTP客户端库.


小智 5

正如@Buhake Sindi的回答一样.如果您使用的是Guava,而不是手动解析,您可以执行以下操作:

MediaType mediaType = MediaType.parse(httpConnection.getContentType());
Optional<Charset> typeCharset = mediaType.charset();
Run Code Online (Sandbox Code Playgroud)