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%以上

相关推荐
摇滚侠8 分钟前
《SpringBoot 3:入门与应用实战》第 7 章 AOP 思想与实现 阅读笔记 15
java·spring boot·笔记
风尘小子26 分钟前
java静态类使用@Value动态绑定环境变量
java
重生之后端学习41 分钟前
239. 滑动窗口最大值[困难]✅
java·数据结构·算法·leetcode·职场和发展
脉动数据行情11 小时前
Java SpringBoot 对接知名台股 TWSE|批量采集上市股票行情实践
java·开发语言·spring boot
她的男孩1 小时前
我把管理系统接给AI,它改条数据都要先问我
java·后端·架构
toolsmith1 小时前
我用AI拆解了Charles的授权机制,发现密钥被写死在了代码里
java·人工智能
IKUN家族2 小时前
SpringBoot日志
java·开发语言
DianSan_ERP2 小时前
WMS接入电商平台自动化履约实战:一张订单从平台到出库的接口时序设计
java·前端·网络·数据库·安全·架构·自动化
liangsheng_g2 小时前
微服务本地开发零配置隔离方案
java·微服务·架构
不服老的小黑哥2 小时前
六、集合处理(collections.md)
java