-
懒羊羊
2024-03-28 55a52ebc929a3ebf2e8dbae450c0c241abf7ff02
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
75
76
package com.jcdm.common.filter;
 
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import com.jcdm.common.utils.http.HttpHelper;
import com.jcdm.common.constant.Constants;
 
/**
 * 构建可重复读取inputStream的request
 * 
 * @author jc
 */
public class RepeatedlyRequestWrapper extends HttpServletRequestWrapper
{
    private final byte[] body;
 
    public RepeatedlyRequestWrapper(HttpServletRequest request, ServletResponse response) throws IOException
    {
        super(request);
        request.setCharacterEncoding(Constants.UTF8);
        response.setCharacterEncoding(Constants.UTF8);
 
        body = HttpHelper.getBodyString(request).getBytes(Constants.UTF8);
    }
 
    @Override
    public BufferedReader getReader() throws IOException
    {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }
 
    @Override
    public ServletInputStream getInputStream() throws IOException
    {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream()
        {
            @Override
            public int read() throws IOException
            {
                return bais.read();
            }
 
            @Override
            public int available() throws IOException
            {
                return body.length;
            }
 
            @Override
            public boolean isFinished()
            {
                return false;
            }
 
            @Override
            public boolean isReady()
            {
                return false;
            }
 
            @Override
            public void setReadListener(ReadListener readListener)
            {
 
            }
        };
    }
}