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

相关推荐
风流 少年16 分钟前
Spring AI 2.0:SSE
java·人工智能·spring
凤山老林41 分钟前
精细化流量治理:Spring Boot 动态特性开关与灰度发布体系
java·spring boot·后端
Aphelios3803 小时前
一次锁内网络IO引发的Tomcat线程池“饿死”事故
java·开发语言·spring boot·elasticsearch·tomcat·网络io阻塞·线程池耗尽
不可求~3 小时前
C++ std::string_view 不是字符串:从悬空引用到安全用法
java·开发语言·c++
Lam Tang3 小时前
APS 系列文章10
java·代理模式
考虑考虑4 小时前
Excel导入时产生特殊字符处理
java·后端·java ee
Scabbards_4 小时前
面试Leetcode - Heap 堆
java·leetcode·面试
程序员清风5 小时前
专业再升级!程序员专属显示器明基RD280UG上手实测!
java·后端·面试
我命由我123456 小时前
RxJava - 冷数据流与热数据流
android·java·java-ee·android studio·rxjava·android-studio·android runtime
Lam Tang6 小时前
APS 系列文章 08
java·代理模式