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

相关推荐
MacroZheng2 分钟前
Claude Code官方桌面端正式发布,夯爆了!
java·人工智能·后端
虚无境10 分钟前
如何编写一个SpringBoot项目告警推送的Starter
java·prometheus·webhook
NE_STOP15 小时前
Vide Coding--AI编程工具的选择
java
码云数智-园园16 小时前
C++20 Modules 模块详解
java·开发语言·spring
程序员黑豆16 小时前
JDK 下载安装与配置详细教程
java·前端·ai编程
小宇宙Zz16 小时前
Maven依赖冲突
java·服务器·maven
swordbob16 小时前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio
咖啡八杯16 小时前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
十五喵源码网17 小时前
基于springboot2+vue2的租房管理系统
java·毕业设计·springboot·论文笔记