eri*_*son 32
一个非常常见的错误是无法将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();
Run Code Online (Sandbox Code Playgroud)