gpt4 book ai didi

Android 字符集问题下载 utf-8 网页

转载 作者:太空狗 更新时间:2023-10-29 13:39:45 26 4
gpt4 key购买 nike

我在下载和解析 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() 但我有长度问题...

一些想法?谢谢!

最佳答案

您需要使用 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();
// ...

然而,它实际上并不允许附加进度监视器。

关于Android 字符集问题下载 utf-8 网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7233156/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com