【问题标题】:Some cyrillic symbols are read incorrectly by Google App Engine's URLConnectionGoogle App Engine 的 URLConnection 无法正确读取某些西里尔符号
【发布时间】:2014-11-01 14:41:31
【问题描述】:

我正在使用简单的代码来检索 JSON 对象。 JSON 采用 Unicode 格式并包含一些西里尔字符。

URL url = new URL("blahblah");
URLConnection con = url.openConnection();
con.setConnectTimeout(10000);
BufferedReader reader = new BufferedReader(new inputStreamReader(con
    .getInputStream()));
String json = reader.readLine();

代码在“标准”Java 实现中运行良好:

Владивосток

但是,当我在 Google App Engine 应用程序中使用相同的 sn-p 时,一些西里尔字母会被替换为 �?字符:

�?ладиво�?�?ок

我注意到,在basic Cyrillic character set 中,只有中半部分(代码为 0421-043F 的符号)被正确读取。不过我不知道该怎么做。

这种行为是由 Google 重新实现 java.net 类引起的,还是我在某处疏忽造成的?

【问题讨论】:

    标签: java google-app-engine unicode character-encoding


    【解决方案1】:

    您必须使用用于在其他服务器/源上创建和发送数据的相同编码。

    InputStreamReader的构造函数中指定相同的编码。

    例如如果你想使用 UTF-8 编码:

    BufferedReader reader = new BufferedReader(new InputStreamReader(
        con.getInputStream(), StandardCharsets.UTF_8));
    

    如果你没有明确指定编码,引用javadoc of the constructor that doesn't take the encoding:

    创建一个使用 default 字符集的InputStreamReader

    因此将使用依赖于平台的默认字符集,因此它在不同操作系统上的工作方式可能不同。所以总是指定字符集。

    编辑:

    建议使用服务器上报的编码。你可以通过URLConnection.getContentEncoding()得到这个:

    BufferedReader reader = new BufferedReader(new InputStreamReader(
        con.getInputStream(), con.getContentEncoding()));
    

    【讨论】:

    • 我尝试将编码显式设置为 StandardCharsets.UTF_8,但效果相反,将所有符号都变为问号。事实证明,JSON 是使用另一种模糊编码创建的,尽管 getContentType() 返回“charset=utf8”。我已经指定了正确的字符集,现在一切正常。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多