PZ_eng 2021-11-23 12:05 采纳率: 50%
浏览 57
已采纳

JAVA Base64 解压解码 中文乱码问题

从第三方应用查询回来的数据在做解压解码的时候发生中文乱码的情况。

/**
 *
 * <p>Description:使用gzip进行解压缩</p>
 * @param compressedStr
 * @return
 */
public static String gunzip(String compressedStr) {
    if (compressedStr == null) {
        return null;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = null;
    GZIPInputStream ginzip = null;
    byte[] compressed = null;
    String decompressed = null;
    try {
        compressed = new sun.misc.BASE64Decoder().decodeBuffer(compressedStr);
        in = new ByteArrayInputStream(compressed);
        ginzip = new GZIPInputStream(in);

        byte[] buffer = new byte[1024];
        int offset = -1;
        while ((offset = ginzip.read(buffer)) != -1) {
            out.write(buffer, 0, offset);
        }
        decompressed = out.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ginzip != null) {
            try {
                ginzip.close();
            } catch (IOException e) {
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }

    return decompressed;
}

应用1 访问 应用2的接口

应用2 访问 第三方应用的接口 查询数据

在应用2中使用上述方法可以对查询回来的数据进行解码,中文未发现乱码情况
当应用2将查询结果原样返回给应用1时,在应用1中使用上述方法可以对查询回来的数据进行解码,发生中文乱码的情况,字符集都是UTF8的
请问这是为什么呢?该如何解决呢。

  • 写回答

2条回答 默认 最新

  • 冰思雨 2021-11-23 13:19
    关注

    decompressed = out.toString(); 换成 decompressed = new String(out.toByteArray(), "UTF-8"); 试一试。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 已采纳回答 11月23日
  • 创建了问题 11月23日

悬赏问题

  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法