【发布时间】:2020-04-30 00:09:54
【问题描述】:
我试图打印出https://top.baidu.com 和https://www.qq.com 的HTML 文本,它们都使用GB2312 字符编码。它正常打印到控制台,除了中文字符,它以不可读的文本形式出现,例如 �㿴���ģ�ȫ�й��...
但是,当我将地址更改为https://www.sina.com.cn 或https://world.taobao.com(两者都使用UTF-8)时,汉字就很好了。
除了恳求百度和QQ转为UTF-8,有什么办法吗?这是我的代码。
try {
String address1 = "https://top.baidu.com"; //unreadable
String address2 = "https://www.qq.com"; //also unreadable
String address3 = "https://www.sina.com.cn"; //readable
String address4 = "https://world.taobao.com"; //readable, too
URL url = new URL(address1);
StringBuilder htmlText = new StringBuilder();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream stream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
int data = reader.read();
while (data != -1) {
char current = (char) data;
htmlText.append(current);
data = reader.read();
}
System.out.println(htmlText);
} catch (Exception e) {
e.printStackTrace();
}
【问题讨论】:
-
new InputStreamReader(stream)- Javadoc 说:创建一个使用 默认字符集的 InputStreamReader。 --- 不是中指定的字符集响应的content-type: text/html; charset=GB2312HTTP 标头。
标签: java html networking character-encoding non-ascii-characters