2010-10-14 98 views
18

我使用URL.openConnection()從服務器下載某些東西。服務器說URLConnection沒有得到字符集

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

connection.getContentEncoding()回報null。怎麼了?

+0

此相關的線程可以幫助其他人:http://stackoverflow.com/questions/9112259/obtaining-response-charset-of-response to-get-or-post-request – Spoonface 2012-12-23 10:39:29

+0

此外還有一個很好的原因connection.getContentEncoding()返回null:它返回http頭的「Content-encoding」字段,**不是**應該給你一個字符集。例如,如果收到的數據是壓縮的,那麼應該使用它,併爲您提供了轉換數據的方式,以便您可以讀取它。 https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 – jdarthenay 2016-03-14 06:25:13

回答

7

爲指定的getContentEncoding()方法返回Content-Encoding HTTP標頭,這是不是在你的例子設置的內容這是記錄的行爲。您可以使用getContentType()方法並自行解析生成的字符串,也可以使用更多的advanced HTTP客戶端庫,如Apache

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"); 
    } 

值相反,而是做一個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 
} 
+0

這些方法被覆蓋以返回OP最可能討論的HttpURLConnection中的理智值,請參閱http:// goo。 gl/wt0P – Waldheinz 2010-10-14 14:46:12

+0

@Waldheinz,謝謝,我想明白了......因此我重新修改了我的帖子.... – 2010-10-14 14:47:52

+0

'substring()'參數應該是'「charset =」。length()+ 1' – bigstones 2013-07-26 08:24:28

5

正如@Buhake Sindi的答案一樣。如果使用的是番石榴,而不是手動解析你可以這樣做:

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