2010-10-14 9 views
18

नहीं मिलता है मैं सर्वर से कुछ डाउनलोड करने के लिए URL.openConnection() का उपयोग कर रहा हूं। सर्वर का कहना हैURLConnection को charset

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

+0

इसके अलावा एक अच्छा कारण कनेक्शन है .getContentEncoding() शून्य देता है: यह http शीर्षलेख का "सामग्री-एन्कोडिंग" फ़ील्ड देता है, जो ** आपको ** देना नहीं है एक चरित्र सेट उदाहरण के लिए इसका उपयोग किया जाना चाहिए यदि प्राप्त डेटा संपीड़ित होता है और आपको डेटा को बदलने के लिए उपयोग करने का तरीका देता है ताकि आप इसे पढ़ सकें। https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 – jdarthenay

उत्तर

7

यह व्यवहार प्रलेखित है के रूप में getContentEncoding() विधि Content-Encoding HTTP शीर्ष लेख है, जो अपने उदाहरण में सेट नहीं है की सामग्री को वापस करने के लिए निर्दिष्ट किया जाता है को शामिल किया है । आप getContentType() विधि का उपयोग कर सकते हैं और परिणामी स्ट्रिंग को अपने आप पर पार्स कर सकते हैं, या संभवतः Apache से एक जैसे advanced HTTP क्लाइंट लाइब्रेरी के लिए जा सकते हैं।

27

मूल्य URLConnection.getContentEncoding() से लौटे 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"); 
    } 

से हैडर Content-Encoding

कोड से मान देता है इसके बजाय, बल्कि एक connection.getContentType() कर सामग्री प्रकार निकालते हैं और सामग्री प्रकार से चारसेट पुनः प्राप्त करने के । मैं ऐसा करने के तरीके पर एक नमूना कोड ....

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

ये विधियां HttpURLConnection में सेन मानों को वापस करने के लिए ओवरराइड की गई हैं, जिनके बारे में ओपी सबसे अधिक संभावना है, http: // goo देखें। gl/wt0P – Waldheinz

+0

@ वाल्डहेन्ज़, धन्यवाद, मैंने यह पता लगाया है ... इसलिए मैंने अपनी पोस्ट दोबारा शुरू कर दी है .... –

+0

'substring() 'तर्क' 'charset =" होना चाहिए। लंबाई() + 1' – bigstones

5

बस @ बुहके सिंडी के उत्तर के अतिरिक्त। आप अमरूद का उपयोग कर रहे हैं, तो मैनुअल पार्स करने के बजाय आप कर सकते हैं:

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