inputStream 和 utf 8 有时显示“?”人物

2024-03-31

所以我已经处理这个问题一个多月了,我还通过谷歌检查了几乎所有可能的相关解决方案,但我找不到任何真正解决我的情况的东西。 我的问题是我正在尝试从网站下载 html 源代码,但在大多数情况下我得到的是某些文本显示一些“?”其中的字符,很可能是因为该网站是希伯来语的。 这是我的代码,

    public static InputStream openHttpGetConnection(String url)
            throws Exception {
        InputStream inputStream = null;
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse httpResponse = httpClient.execute(new HttpGet(url));
        inputStream = httpResponse.getEntity().getContent();
        return inputStream;

    }
    public static String downloadSource(String url) {
        int BUFFER_SIZE = 1024;

        InputStream inputStream = null;
        try {
            inputStream = openHttpGetConnection(url);
        } catch (Exception e) {
            // TODO: handle exception
        }
        int bytesRead;
        String str = "";
        byte[] inpputBuffer = new byte[BUFFER_SIZE];
        try {
            while ((bytesRead = inputStream.read(inpputBuffer)) > 0) {
                String read = new String(inpputBuffer, 0, bytesRead,"UTF-8");
                str +=read;

            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return str;

    }

Thanks.


要从给定编码的字节流中读取字符,请使用Reader。在你的情况下,它会是这样的:

    InputStreamReader isr = new InputStreamReader(inpputStream, "UTF-8");
    char[] inputBuffer = new char[BUFFER_SIZE];

    while ((charsRead = isr.read(inputBuffer, 0, BUFFER_SIZE)) > 0) {
        String read = new String(inputBuffer, 0, charsRead);
        str += read;
    }

您可以看到字节将直接作为字符读入——读者的问题是知道是否需要读取一个或两个字节,例如,在缓冲区中创建字符。这基本上是您的方法,但是在读入字节时进行解码,而不是在读入字节之后进行解码。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

inputStream 和 utf 8 有时显示“?”人物 的相关文章

随机推荐