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

相关推荐
码云数智-园园17 小时前
Java中的重载(Overload)与重写(Override):本质区别、场景与注意事项
java·开发语言
yxm263366908117 小时前
洛谷P1217回文质数
java·开发语言
金斗潼关17 小时前
java反序列化入口方法介绍
java·开发语言·jvm·序列化·反序列化
一直都在57217 小时前
Java并发面经(二)
java·开发语言·spring
小雷君17 小时前
SpringBoot 接口开发5个高频踩坑总结
java·spring boot·后端·面试
aloha_78917 小时前
软考高项-第二章-信息技术发展
java·人工智能·python·学习
寒秋花开曾相惜17 小时前
(学习笔记)3.8 指针运算(3.8.5 变长数组)
java·c语言·开发语言·笔记·学习
途经六月的绽放18 小时前
常见设计模式及其应用示例
java·设计模式
REI-18 小时前
黑马点评项目启动
java·后端
AlunYegeer18 小时前
【JAVA】网关的管理原理和微服务的Interceptor区分
java·服务器·前端