2010-10-14 94 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(); 
相关问题