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 小时前
Java 集合算法:从排序、查找到底层原理的实战指南
java·python·算法
devpotato1 小时前
缓存与数据库更新顺序不一致问题
java·数据库·redis
xcl09251 小时前
酒馆预约系统开发实战:从需求分析到上线全流程指南
java·spring boot·需求分析
Kyrie_kk2 小时前
Java--IO--Path文件访问
java·后端
qinqinzqq2 小时前
Maven POM 格式、Schema 与 XSD:一篇讲透
java·maven
o盟2 小时前
maven本地仓库有 总是去私仓中下载
java·maven·intellij-idea
devpotato2 小时前
Java 批量并发请求:从“能并发“到“结果按完成顺序可用“的三种写法与选型
java
苏生Susheng3 小时前
【软件实施】Linux企业运维常用命令手册
java·linux·运维·服务器·springboot·springcloud·软件实施
想要成为老金高手3 小时前
Kubernetes 调度器详解:从 nodeName 到污点容忍
java·容器·kubernetes
吴长建先生重名了3 小时前
ElasticSearch 检索系统性能优化实战:基准测试
java