Olá!
Existe uma forma de eu decodificar uma String para um charset padrão?
Meu problema é o seguinte: tenho que conectar à vários servidores HTTP, que podem ter diferentes codificações, e retornar o conteúdo da página HTML, mas em alguns casos, caracteres “estranhos” aparecem devido a diferença de codificação.
Fiz um esquema assim:
[code]public String connect() throws IOException {
String content = “”;
if (getConnection() != null) {
getConnection().connect();
if (getConnection().getResponseCode() == 200) {
InputStream in = getConnection().getInputStream();
String contentType = getConnection().getHeaderField("content-type");
if (contentType != null && contentType.toLowerCase().contains("utf-8")) {
Charset utf8 = Charset.forName("UTF-8");
CharsetDecoder decoder = utf8.newDecoder();
int c;
List<Byte> bList = new Vector<Byte>();
while ((c = in.read()) != -1)
bList.add(new Byte((byte) c));
byte[] bArray = new byte[bList.size()];
int i = 0;
for (Byte b : bList)
bArray[i++] = b.byteValue();
CharBuffer chrBuf = decoder.decode(ByteBuffer.wrap(bArray));
content = chrBuf.toString();
} else {
int c;
StringBuffer buf = new StringBuffer();
while ((c = in.read()) != -1)
buf.append((char) c);
content = buf.toString();
}
in.close();
}
}
setContent(content);
return content;
}[/code]
O problema é que, em alguns casos, a seguinte exceção é lançada:
java.nio.charset.MalformedInputException: Input length = 1
at java.nio.charset.CoderResult.throwException(CoderResult.java:260)
at java.nio.charset.CharsetDecoder.decode(CharsetDecoder.java:771)
Existe também situações em que o Content-type não é informado no Header.
Alguém tem alguma sugestão de como eu posso decodificar a página independentemente das informações do Header HTTP?
Obrigado!