houzhongjian
2024-07-23 a6de490948278991e47952e90671ddba4555e9a2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.iailab.module.data.framework.filter;
 
import groovy.util.logging.Slf4j;
import lombok.Getter;
 
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
 
@Slf4j
@Getter
public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {
    /** 复制请求body */
    private final String body;
 
    public MyHttpServletRequestWrapper (HttpServletRequest request) {
        super(request);
        try {
            //设置编码格式, 防止中文乱码
            request.setCharacterEncoding("UTF-8");
            //将请求中的流取出来放到body里,后面都只操作body就行
            this.body = RequestReadUtils.read(request);
        } catch (Exception e) {
            throw new RuntimeException("MyHttpServletRequestWrapper 拦截器异常");
        }
    }
 
    @Override
    public ServletInputStream getInputStream()  {
        //返回body的流信息即可
        try(final ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes())){
            return getServletInputStream(bais);
        }catch(IOException e){
            throw new RuntimeException("MyHttpServletRequestWrapper 获取input流异常");
        }
    }
 
    @Override
    public BufferedReader getReader(){
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
 
    /**
     * 重写getInputStream流
     * @param bais
     * @return
     */
    private static ServletInputStream getServletInputStream(ByteArrayInputStream bais) {
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }
 
            @Override
            public boolean isReady() {
                return false;
            }
 
            @Override
            public void setReadListener(ReadListener readListener) {
            }
            @Override
            public int read() {
                return bais.read();
            }
        };
    }
}