【问题标题】:Cannot get URL content as UTF-8无法以 UTF-8 格式获取 URL 内容
【发布时间】:2013-03-08 14:48:31
【问题描述】:

我正在尝试从 URL 读取内容,但它确实返回了奇怪的符号,而不是“è”、“à”等。

这是我正在使用的代码:

public static String getPageContent(String _url) {
    URL url;
    InputStream is = null;
    BufferedReader dis;
    String line;
    String text = "";
    try {
        url = new URL(_url);
        is = url.openStream();

        //This line should open the stream as UTF-8
        dis = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        while ((line = dis.readLine()) != null) {
            text += line + "\n";
        }
    } catch (MalformedURLException mue) {
        mue.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException ioe) {
            // nothing to see here
        }
    }
    return text;
}

我看到其他类似的问题,所有的回答都是这样的

Declare your inputstream as 
new InputStreamReader(is, "UTF-8")

但我无法让它工作。

例如,如果我的url内容包含

è uno dei più

我明白了

è uno dei più

我错过了什么?

【问题讨论】:

    标签: java url utf-8 inputstream


    【解决方案1】:

    从你的例子来看。您确实收到了多字节 UTF-8 字节流,但您的文本编辑器读取为 ISO-8859-1。告诉您的编辑器将字节读取为 UTF-8!

    【讨论】:

      【解决方案2】:

      我真的不知道为什么这不起作用,但是 Java 7 方法是使用 StandardCharsets.UTF_8 请参阅

      http://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html

      在(新的)Constructor InputStreamReader(InputStream in, Charset cs)中,见

      http://docs.oracle.com/javase/7/docs/api/java/io/InputStreamReader.html.

      【讨论】:

        猜你喜欢
        • 2017-04-29
        • 2012-10-05
        • 1970-01-01
        • 1970-01-01
        • 2014-01-24
        • 1970-01-01
        • 1970-01-01
        • 2018-04-24
        • 2015-03-15
        相关资源
        最近更新 更多