【问题标题】:Chinese characters from HTML text print properly for some websites, but not others来自 HTML 文本的中文字符在某些网站上可以正确打印,但在其他网站上则不行
【发布时间】:2020-04-30 00:09:54
【问题描述】:

我试图打印出https://top.baidu.comhttps://www.qq.com 的HTML 文本,它们都使用GB2312 字符编码。它正常打印到控制台,除了中文字符,它以不可读的文本形式出现,例如 �㿴���ģ�ȫ�й��...

但是,当我将地址更改为https://www.sina.com.cnhttps://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=GB2312 HTTP 标头。

标签: java html networking character-encoding non-ascii-characters


【解决方案1】:

在阅读了 Andreas 的评论后,我查找了 InputStreamReader 的替代构造函数并想出了以下内容。

InputStreamReader reader = new InputStreamReader(stream, Charset.forName("GB2312"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 2018-07-03
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多