下载utf-8网页的Android charset问题

时间:2011-08-29 16:49:04

标签: android utf-8 character-encoding download

我在下载和解析UTF-8网页时遇到问题...我使用下一个函数来获取网页的HTML:

static String getString(String url, ProgressDialog loading) {
    String s = "", html = "";
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        conn.connect();
        DataInputStream dis = new DataInputStream(conn.getInputStream());
        loading.setTitle("Descargando...");
        loading.setMax( 32000 );
        while ((s = dis.readLine()) != null) {
            html += s;
            loading.setProgress(html.length());
        }
    } catch (Exception e) {
        Log.e("CC", "Error al descargar: " + e.getMessage());

    } finally {
        if (conn != null)
            conn.disconnect();
    }
    return html;
}

网页上有:

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />

但是西班牙语的元素如下:应用程序中出现错误的ééóó。我尝试使用readUTF(),但我有长度问题......

一些想法?谢谢!

2 个答案:

答案 0 :(得分:1)

我很确定你不想使用DataInputStream。

这个答案可能会有所帮助:Read/convert an InputStream to a String

答案 1 :(得分:1)

您需要使用Reader指定用于读取输入流的字符集。在这种特殊情况下,您需要InputStreamReader

Reader reader = null;
StringBuilder builder = new StringBuilder();

try {
    // ...
    reader = new InputStreamReader(connection.getInputStream(), "UTF-8");
    char[] buffer = new char[8192];

    for (int length = 0; (length = reader.read(buffer)) > 0;) {
        builder.append(buffer, 0, length);
        loading.setProgress(length);
    }
} finally {
    if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}

String html = builder.toString();
// ...

对具体问题

无关,您是否考虑使用像Jsoup这样的HTML解析器?它会将这些令人讨厌的细节考虑在内。然后就像

一样简单
String html = Jsoup.connect(url).get().html();
// ...

然而,它并不真正允许附加进度监视器。