spring boot 中,使用拦截器 把返回结果中的空字符串替换成”-“,并压缩数据(从response中得到响应结果并处理)

说明 :如果项目中有导出, 则不能使用这个方法,参考另一篇文章
https://blog.csdn.net/qq_26634873/article/details/123679174

第一步

package com.cpiinfo.iot.isolar.config;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.*;

public class ResponseWrapper extends HttpServletResponseWrapper {

    private ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    private HttpServletResponse response;
    private PrintWriter pwrite;

    public ResponseWrapper(HttpServletResponse response) {
        super(response);
        this.response = response;
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return new MyServletOutputStream(bytes); // 将数据写到 byte 中
    }

    /**
     * 重写父类的 getWriter() 方法,将响应数据缓存在 PrintWriter 中
     */
    @Override
    public PrintWriter getWriter() throws IOException {
        try{
            pwrite = new PrintWriter(new OutputStreamWriter(bytes, "utf-8"));
        } catch(UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return pwrite;
    }

    /**
     * 获取缓存在 PrintWriter 中的响应数据
     * @return
     */
    public byte[] getBytes() {
        if(null != pwrite) {
            pwrite.close();
            return bytes.toByteArray();
        }

        if(null != bytes) {
            try {
                bytes.flush();
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
        return bytes.toByteArray();
    }

    class MyServletOutputStream extends ServletOutputStream {
        private ByteArrayOutputStream ostream ;

        public MyServletOutputStream(ByteArrayOutputStream ostream) {
            this.ostream = ostream;
        }

        @Override
        public void write(int b) throws IOException {
            ostream.write(b); // 将数据写到 stream 中
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {

        }
    }

}

第二步

package com.cpiinfo.iot.isolar.config;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

/**
 * @description:
 * @author: fan
 * @date: 2022/3/22 10:08
 * @version: 1.0
 */
@Component
public class EmptyToRungFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String headEncoding = ((HttpServletRequest) servletRequest).getHeader("accept-encoding");
        if (headEncoding == null || (headEncoding.indexOf("gzip") == -1)) { // 客户端 不支持 gzip
            filterChain.doFilter(servletRequest, servletResponse);
            System.out.println("----------------该浏览器不支持gzip格式编码-----------------");
        } else { // 支持 gzip 压缩,对数据进行gzip压缩

            HttpServletRequest req = (HttpServletRequest) servletRequest;
            HttpServletResponse resp = (HttpServletResponse) servletResponse;
            ResponseWrapper mResp = new ResponseWrapper(resp); // 包装响应对象 resp 并缓存响应数据

            filterChain.doFilter(req, mResp);

            byte[] bytes = mResp.getBytes(); // 获取缓存的响应数据
            System.out.println("压缩前大小:" + bytes.length);
            System.out.println("压缩前数据:" + new String(bytes, "utf-8"));

            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            GZIPOutputStream gzipOut = new GZIPOutputStream(bout); // 创建 GZIPOutputStream 对象

            String result = new String(bytes, "utf-8");
            String replaceAllResult = result.replaceAll("\"\"", "\"-\"");
            System.out.println(replaceAllResult);


            gzipOut.write(replaceAllResult.getBytes()); // 将响应的数据写到 Gzip 压缩流中
            gzipOut.flush();
            gzipOut.close(); // 将数据刷新到  bout 字节流数组

            byte[] bts = bout.toByteArray();
            System.out.println("压缩后大小:" + bts.length);
            resp.setHeader("Content-Encoding", "gzip"); // 设置响应头信息
            resp.getOutputStream().write(bts); // 将压缩数据响应给客户端
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值