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

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日

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据