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

相关推荐
其美杰布-富贵-李21 分钟前
Spring Boot 依赖注入说明文档
java·spring boot·python
tachibana226 分钟前
hot100 数组中的第K个最大元素(215)
java·数据结构·算法·leetcode
our_times31 分钟前
2026年Java开发者破局指南:Spring AI 2.0 与 Agent 开发实战
java·人工智能·spring
糖果店的幽灵1 小时前
langgraph的四种state解析
java·前端·javascript·langgraph
杨充1 小时前
4.接口而非实现编程
java·后端·架构
梦梦代码精1 小时前
基于ThinkPHP6 + Vue3的家政预约系统全解析:从LBS定位到自动派单的完整实现
java·docker·开源·php·代码规范
wear工程师1 小时前
@Transactional 标了却没开事务?先看这次调用有没有经过代理
java·spring
Joey_friends2 小时前
指纹authenticate流程图
android·java·c++
郑州光合科技余经理2 小时前
家政O2O平台解析:从0搭建上门预约小程序解决方案
android·java·开发语言·前端·小程序·架构·php
野蛮人6号2 小时前
黑马天机学堂系列问题之域名无法正常使用
java·spring cloud·天机学堂