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

相关推荐
甲枫叶1 小时前
【claude】Claude Code正式引入Git Worktree原生支持:Agent全面实现并行独立工作
java·人工智能·git·python·ai编程
六件套是我2 小时前
无法访问org.springframeword.beans.factory.annotation.Value
java·开发语言·spring boot
LYS_06182 小时前
C++学习(5)(函数 指针 引用)
java·c++·算法
forestsea2 小时前
Spring Cloud Alibaba 2025.1.0.0 正式发布:拥抱 Spring Boot 4.0 与 Java 21+ 的新时代
java·spring boot·后端
IT枫斗者2 小时前
IntelliJ IDEA 2025.3史诗级更新:统一发行版+Spring Boot 4支持,这更新太香了!
java·开发语言·前端·javascript·spring boot·后端·intellij-idea
forestsea2 小时前
Spring Boot 4.0 + JDK 25 + GraalVM:下一代云原生Java应用架构
java·spring boot·云原生
♡喜欢做梦2 小时前
Spring Boot 日志实战:级别、持久化与 SLF4J 配置全指南
java·spring boot·后端·spring·java-ee·log4j
青衫码上行2 小时前
【项目部署】Spring Boot项目部署的四种方式
java·linux·服务器·spring boot·后端·docker·腾讯云
想不明白的过度思考者2 小时前
你真的会打印日志吗?基于 Spring Boot 的全方位日志指南
java·spring boot·后端·日志