簡體   English   中英

URLConnection沒有得到charset

[英]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
}

這是記錄的行為,因為指定了getContentEncoding()方法以返回Content-Encoding HTTP標頭的內容,該標頭未在您的示例中設置。 您可以使用getContentType()方法並自行解析生成的String,也可以使用Apache中高級的 HTTP客戶端庫。

正如@Buhake Sindi的回答一樣。 如果您使用的是Guava,而不是手動解析,您可以執行以下操作:

MediaType mediaType = MediaType.parse(httpConnection.getContentType());
Optional<Charset> typeCharset = mediaType.charset();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM