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

相关推荐
IvorySQL4 分钟前
云环境下PostgreSQL的Cgroup内存管理实践
java·数据库·postgresql
不定积分要+C_yyy6 分钟前
Java基础核心精讲:基本数据类型与包装类区别、自动装箱拆箱与缓存陷阱实战解析
java·开发语言
jvmind_dev6 分钟前
第三章:GC 日志深度分析(上)——多版本、多收集器的统一解析
java·agent
xingxiliang8 分钟前
ReliableAgent:类似工程级可用的agent示例
java·开发语言·agent
亦暖筑序21 分钟前
AgentScope-Java 入门:保存评审状态并生成 Markdown 报告
java·人工智能·后端
invicinble39 分钟前
关于微服务基本框架搭建--fegin最小使用demo
java·spring boot·微服务
梦想的旅途239 分钟前
企业微信API 实现企业微信消息的自动发送?
java·服务器·前端
大不点wow1 小时前
为什么 Spring 更推荐构造器注入,而不是字段 `@Autowired`
java·spring·intellij-idea
用户298698530141 小时前
Java 创建 CSV 文件的三种实用方法:从零构建、数组写入与 Excel 转换
java·后端·excel
Cry丶1 小时前
一次 FTP 上传引发 504 Gateway Timeout 的排查复盘
java·nginx·ftp·openresty·被动模式·504 gateway·生产问题排查