91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

springBoot之怎么獲取接口請求數據和返回數據實現日志

發布時間:2023-04-08 17:48:20 來源:億速云 閱讀:197 作者:iii 欄目:開發技術

這篇文章主要介紹“springBoot之怎么獲取接口請求數據和返回數據實現日志”,在日常操作中,相信很多人在springBoot之怎么獲取接口請求數據和返回數據實現日志問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”springBoot之怎么獲取接口請求數據和返回數據實現日志”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

    一、獲取接口請求的數據

    可以在Interceptor的afterCompletion中實現但是要重寫RequestWrapper

    代碼記錄如下:

    HttpServletRequestFilter

    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
     
    import org.springframework.core.annotation.Order;
    import org.springframework.stereotype.Component;
     
    import java.io.IOException;
     
    @Component
    @WebFilter(filterName = "HttpServletRequestFilter", urlPatterns = "/")
    @Order(10000)
    public class HttpServletRequestFilter implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
     
        }
     
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            ServletRequest requestWrapper = null;
            if(servletRequest instanceof HttpServletRequest) {
                requestWrapper = new RequestWrapper((HttpServletRequest) servletRequest);
            }
            //獲取請求中的流如何,將取出來的字符串,再次轉換成流,然后把它放入到新request對象中
            // 在chain.doFiler方法中傳遞新的request對象
            if(null == requestWrapper) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                filterChain.doFilter(requestWrapper, servletResponse);
            }
        }
     
        @Override
        public void destroy() {
     
        }
     
    }

    RequestWrapper

    import javax.servlet.ReadListener;
    import javax.servlet.ServletInputStream;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletRequestWrapper;
    import java.io.*; 
     
    public class RequestWrapper extends HttpServletRequestWrapper {
        private final String body;
     
        public RequestWrapper(HttpServletRequest request) {
            super(request);
            StringBuilder stringBuilder = new StringBuilder();
            BufferedReader bufferedReader = null;
            InputStream inputStream = null;
            try {
                inputStream = request.getInputStream();
                if (inputStream != null) {
                    bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    char[] charBuffer = new char[128];
                    int bytesRead = -1;
                    while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                        stringBuilder.append(charBuffer, 0, bytesRead);
                    }
                } else {
                    stringBuilder.append("");
                }
            } catch (IOException ex) {
     
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            body = stringBuilder.toString();
        }
     
        @Override
        public ServletInputStream getInputStream() throws IOException {
            final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
            ServletInputStream servletInputStream = new ServletInputStream() {
                @Override
                public boolean isFinished() {
                    return false;
                }
                @Override
                public boolean isReady() {
                    return false;
                }
                @Override
                public void setReadListener(ReadListener readListener) {
                }
                @Override
                public int read() throws IOException {
                    return byteArrayInputStream.read();
                }
            };
            return servletInputStream;
     
        }
     
        @Override
        public BufferedReader getReader() throws IOException {
            return new BufferedReader(new InputStreamReader(this.getInputStream()));
        }
     
        public String getBody() {
            return this.body;
        }
     
    }

    afterCompletion

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception)
                throws Exception {
     
            logger.debug("SessionInterceptor");
            // 獲取地址
            String url = request.getRequestURL().toString();
            String requestMethod = request.getMethod();
            String servletPath = request.getServletPath();
            String body = new RequestWrapper(request).getBody();
            String contentType = request.getContentType();
            Map reqMap = new HashMap();
            if(requestMethod.equals("POST")) {
                if(!contentType.equals("text/plain")) 
                    body = "body is file,don't show.";
                if(body.length()>1000) 
                    body = body.substring(0, 1000);
            }
            if(requestMethod.equals("GET")) {
                // 獲取請求參數
                Map ParameterMap =  request.getParameterMap();
                Set<Map.Entry<String,String[]>> entry = ParameterMap.entrySet();
                Iterator<Map.Entry<String,String[]>> it = entry.iterator();
                while (it.hasNext()){
                    Map.Entry<String,String[]>  me = it.next();
                    String key = me.getKey();
                    String value = me.getValue()[0];
                    reqMap.put(key,value);
                }
            }
            logger.error("url: "+url+",requestMethod: "+requestMethod+",servletPath: "+servletPath+",body: " + body+",parameterMap: "+reqMap.toString());
            
            
        }

    二、獲取接口返回的數據

    可以在filter中實現但是要重寫ResponseWrapper,

    代碼記錄如下:

    HttpServletResponseFilter

    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
     
    import org.apache.log4j.Logger;
    import org.springframework.core.annotation.Order;
    import org.springframework.stereotype.Component;
     
    import java.io.IOException;
     
    @Component
    @WebFilter(filterName = "HttpServletResponseFilter", urlPatterns = "/")
    @Order(10000)
    public class HttpServletResponseFilter implements Filter {
        static Logger logger = Logger.getLogger(HttpServletResponseFilter.class.getName());
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
     
        }
     
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletRequest req = (HttpServletRequest) servletRequest;
            HttpServletResponse resp = (HttpServletResponse) servletResponse;
            ResponseWrapper mResp = new ResponseWrapper(resp); // 包裝響應對象 resp 并緩存響應數據
            filterChain.doFilter(req, mResp);
            byte[] bytes = mResp.getBytes(); // 獲取緩存的響應數據
            logger.error(new String(bytes,"utf-8"));
        }
     
        @Override
        public void destroy() {
     
        }
     
    }

    ResponseWrapper

    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() {
                // TODO Auto-generated method stub
                return false;
            }
     
            @Override
            public void setWriteListener(WriteListener listener) {
                // TODO Auto-generated method stub
                
            }
     
        }
     
    }

    到此,關于“springBoot之怎么獲取接口請求數據和返回數據實現日志”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!

    向AI問一下細節

    免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

    AI

    安国市| 包头市| 东城区| 永安市| 惠州市| 锦屏县| 民权县| 安泽县| 班戈县| 广德县| 天祝| 子长县| 富源县| 铅山县| 高雄县| 丰镇市| 恩平市| 漾濞| 津南区| 南安市| 通榆县| 嵩明县| 西安市| 永胜县| 广汉市| 姚安县| 香格里拉县| 宣武区| 同心县| 门源| 鹤岗市| 德令哈市| 赤峰市| 永善县| 广丰县| 阿坝| 黄平县| 建德市| 咸阳市| 龙井市| 贵定县|