java.nio.charset.IllegalCharsetNameException: 'ISO-8859-1'
Jsoup.connect("http://www.design.cmu.edu/community.php?s=3").get();
有人可以告诉我为什么代码给了我错误:
java.nio.charset.IllegalCharsetNameException: 'ISO-8859-1'
解答:
问题出在目标页面上。它根本不是格式良好的。
解析页面时,JSoup 尝试修复页面,一方面,将内容类型解析为“text/html; charset='iso-8859-1'”(包括单引号)。
然后它传递这个字符串(带单引号)并使用它来获取字符集:
Charset.forName("'ISO-8859-1'");
这失败了。
问题出在目标页面上。也许您可以改用这种替代方法,它不会解析页面中的字符集,因为您显式地传递了它:
String url = "http://www.design.cmu.edu/community.php?s=3";
Document document = Jsoup.parse(new URL(url).openStream(), "ISO-8859-1", url);
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> //正确
<meta http-equiv="content-type" content="text/html;charset=utf-8" /> //错误
出现异常:java.nio.charset.IllegalCharsetNameException: utf-8,gbk
所以解析获取的字符集有错,使用它便会出错,可以先获取后解析
上面是第一种方法:
下面是第二种方法,都是先获取后解析
public String getJson(String httpurl) {
BufferedReader in = null;
String result = "";
try {
// 发送http请求
URL url = new URL(httpurl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestProperty("Accept", "*/*");
// 建立实际的连接
httpConn.connect();
// 定义BufferedReader输入流来读取URL的响应,并设置编码方式
in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
String line;
// 读取返回的内容
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}