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

相关推荐
2601_955759887 分钟前
如何识别 Claude API 低价值调用并优化
java
鹿角片ljp44 分钟前
Java框架篇:Spring + SpringMVC + SpringBoot + MyBatis深度复习
java·开发语言
Lyra_Infra1 小时前
Java 应用启动脚本 JDK 路径适配优化文档
java·shell
CodeHackerBhx2 小时前
Spring Boot 4 防重复提交:从接口幂等到 Redis 分布式锁的完整实践
java·数据库·spring boot·redis·分布式
八角.。2 小时前
方法参数与Debug按键
java·开发语言·jvm
BerryS3N2 小时前
Java在人工智能与大模型时代的深度演进:从工程落地、高性能计算到企业级Agent与RAG架构实战指南
java·人工智能·架构
蔬菜_2 小时前
前端转全栈-day2(修饰符)
java
fīɡЙtīиɡ ℡2 小时前
怎么是用JWT
java·状态模式
唐青枫2 小时前
Java JCommander 实战详解:用注解解析命令行参数
java
步行cgn3 小时前
carList.forEach(System.out::println)
java·开发语言·mybatis