Google App Engine的URLConnection错误地读取了一些西里尔符号

时间:2014-11-01 14:41:31

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

我正在使用简单的代码来检索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应用程序中使用相同的代码段时,一些西里尔字母会被替换为 ?字符:

  

?ладиво??ок

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

这种行为是由Google重新实现java.net课程引起的,还是我在某处监督?

1 个答案:

答案 0 :(得分: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

  

创建使用默认字符集的InputStreamReader

因此将使用平台相关的默认字符集,因此它可能在不同的操作系统上有所不同。所以总是指定字符集。

修改

建议使用服务器报告的编码。您可以通过URLConnection.getContentEncoding()

获取此信息
BufferedReader reader = new BufferedReader(new InputStreamReader(
    con.getInputStream(), con.getContentEncoding()));