正如标题所说的那样。
帮助不胜感激!
最佳答案
一个极其常见的错误是未能正确地将 HTTP 响应从字节转换为字符。为此,您必须知道响应的字符编码。希望这被指定为“Content-Type”参数中的参数。但是将它放在正文本身中,作为 meta
标记中的“http-equiv”属性也是一种选择。
因此,将页面正确加载到 String
中是非常复杂的,甚至像 HttpClient 这样的第三方库也不提供通用解决方案。
这是一个处理最常见情况的简单实现:
URL url = new URL("http://stackoverflow.com/questions/1381617");
URLConnection con = url.openConnection();
Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
Matcher m = p.matcher(con.getContentType());
/* If Content-Type doesn't match this pre-conception, choose default and
* hope for the best. */
String charset = m.matches() ? m.group(1) : "ISO-8859-1";
Reader r = new InputStreamReader(con.getInputStream(), charset);
StringBuilder buf = new StringBuilder();
while (true) {
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
}
String str = buf.toString();
关于java - 将 html 从网页正确加载到 Java 中的字符串的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1381617/