JAVA HTTP压缩数据

java 复制代码
/**
     * 压缩数据包
     *
     * @param code
     * @param data
     * @param resp
     * @throws IOException
     */
    protected void writeZipResult(int code, Object data, HttpServletResponse resp) throws IOException {
        resp.setHeader("Content-Encoding", "gzip");
        // write到客户端
        resp.setContentType("application/json;charset=utf-8");
        ApiResult ret = new ApiResult();
        ret.setData(data);
        ret.setCode(code);
        byte[] compressedData = null;
        ByteArrayOutputStream baos = null;
        GZIPOutputStream gzos = null;
        byte[] bytes = null;
        try {
            baos = new ByteArrayOutputStream();
            gzos = new GZIPOutputStream(baos);
            bytes = JSON.toJSONString(ret).getBytes(StandardCharsets.UTF_8);
            gzos.write(bytes);
            gzos.finish();
            compressedData = baos.toByteArray();
            logger.info("Original data len:{} after compression len:{} compression rate:{}", bytes.length, compressedData.length, compressedData.length * 1.0 * 100 / bytes.length);
        } catch (Exception e) {
            logger.error("Compressed data is abnormal", e);
        } finally {
            if (gzos != null) {
                gzos.close();
            }
            if (baos != null) {
                baos.close();
            }
        }
        if (compressedData != null) {
            // 设置Content-Length
            resp.setContentLength(compressedData.length);
            resp.getOutputStream().write(compressedData);
            resp.getOutputStream().flush();
        }
    }

压缩结果能达到 90%以上

相关推荐
Pniubi9 小时前
怎么排查慢SQL,怎么解决?
java·数据库·sql
薛之谦_10 小时前
Java 全栈知识体系:从 IDEA 高效开发到 JVM、并发与 Stream 实战
java·jvm·intellij-idea
文丑颜不良啊14 小时前
LeetCode2761~2780题目解析
java·leetcode
IT枫斗者枫哥14 小时前
子线程断言失败,JUnit 为什么还显示通过?
java·后端
考虑考虑16 小时前
JDK27中的Set.ofLazy
java·后端·java ee
文丑颜不良啊17 小时前
LeetCode2841~2860题目解析
java·leetcode
小南家的青蛙17 小时前
Tomcat与Jetty深度对比
java·tomcat·jetty
乌暮18 小时前
Spring AOP 与 Spring 事务:用大白话彻底理解原理与实践
java·数据库·spring boot·后端·sql·学习·spring
YDS82918 小时前
Small Spring IOC篇:容器事件及其监听器
java·spring
金銀銅鐵18 小时前
带您看懂字节码指令(三):一行加法里有什么
java·jvm