URLConnection no recibe el conjunto de caracteres
-
30-09-2019 - |
Pregunta
Estoy usando URL.openConnection()
descargar algo desde un servidor. El servidor dice
Content-Type: text/plain; charset=utf-8
pero vuelve connection.getContentEncoding()
null
. ¿Qué pasa?
Solución
Esto está documentado comportamiento como se especifica el método getContentEncoding()
para devolver el contenido de la cabecera HTTP Content-Encoding
, que no se encuentra en su ejemplo. Se podría utilizar el método getContentType()
y analizar la cadena resultante por su cuenta, o posiblemente ir a dar un mayor avanzó HTTP biblioteca cliente como el de Apache .
Otros consejos
El valor devuelto de URLConnection.getContentEncoding()
devuelve el valor de la cabecera Content-Encoding
Código de 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");
}
En su lugar, prefiere hacer una connection.getContentType()
para recuperar el tipo de contenido y recuperar el juego de caracteres del tipo de contenido. He incluido un código de ejemplo sobre cómo hacer esto ....
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
}
Así como una adición a la respuesta de @Buhake Sindi. Si está utilizando la guayaba, en lugar del análisis manual le puede hacer:
MediaType mediaType = MediaType.parse(httpConnection.getContentType());
Optional<Charset> typeCharset = mediaType.charset();