android - 如何显示中文字符来自inuptstream

时间:2016-08-02 01:46:24

标签: android

当我在php文件中输出英文字符串时,应用程序可以通过toast从输入流显示该消息。但是,当我在php文件中输出中文字符串时,我将以下代码转换为UTF-8,我无法获得中文字符串。

的java:

InputStream IS = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS,"ISO-8859-1"));
StringBuilder result = new StringBuilder();
String getresult = "";
while((getresult = bufferedReader.readLine()) != null){
       result.append(getresult);
}
bufferedReader.close();
IS.close();
String resultstring = result.toString();
return resultstring.getBytes("UTF-8").toString();

当我进行转换时,消息显示非中文字符串。如何显示从服务器获取中文字符串。

2 个答案:

答案 0 :(得分:1)

您应该将所有编码更改为utf-8,并且php文件中输出的中文字符串应使用utf-8编码。

答案 1 :(得分:1)

从网络接收UTF-8字符串:

public static final Charset CHARSET_UTF8 = Charset.forName("UTF-8");

public static String receiveUtf8String(final InputStream is) throws Throwable {
    if (null == is) return null;
    final BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(is, CHARSET_UTF8));
    StringBuilder result = new StringBuilder();
    String getresult = "";
    while ((getresult = bufferedReader.readLine()) != null) {
        result.append(getresult);
        //BTW, this will join multiple lines into single one!
    }
    bufferedReader.close();
    is.close();
    return result.toString();
}

测试它:

    //的 in UTF-8 for test
    final byte[] buf = {(byte) 0xE7, (byte) 0x9A, (byte) 0x84};
    final ByteArrayInputStream is = new ByteArrayInputStream(buf);
    try {
        String test = receiveUtf8String(is);
        System.out.println("Test: " + test);
    } catch (Throwable throwable) {
        System.out.println("ERROR: " + throwable.getMessage());
    }

关于服务器编码为ISO-8859-1。 嗯,这很糟糕,因为严格来说,当发送到ISO-8859-1输出时会损坏UTF-8字符串。

所以正确的方法是将服务器端编码修复为Utf8,如果你想发送Utf8字符串。

但是如果服务器没有进行任何强编码验证,并且你在输出上发送Utf8字节(直接,没有任何转换),它可能会以Utf8字节为低(因为Utf8通常几乎向后兼容8b扩展ASCII,ISO-8859-1也是8位编码。

因此,首先验证从服务器接收的字节数,如果它是未损坏的Utf8(请参阅我的示例,了解该单字形编码)。如果没有,请重新配置服务器。

你不想在任何地方使用ISO-8859-1,为什么?它毫无用处。 ISO-8859-1可以处理的所有东西都可以处理Utf-8,但是Utf-8也可以处理国际字形(虽然如果你要发送很多中国字形,你可以考虑使用Utf-16服务器端,减少50%的流量。)