SpringBoot过滤器获取请求Body

package com.example.springboot.core;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

/**
 * @Auther: qint
 * @Date: 2023/03/01 16:57
 * @Description:
 */

@Slf4j
public class RequestWrapper extends HttpServletRequestWrapper {
    private String body;
    public RequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        body=getBodyStr(request);
    }

    public String getBodyStr(){
        return  body;
    }
//方法1
//  private String getBodyStr(HttpServletRequest request) throws IOException {
//
//      BufferedReader reader=request.getReader();
//      String line=null;
//      StringBuilder stringBuilder=new StringBuilder();
//       while ((line=reader.readLine())!=null){
//
//           stringBuilder.append(line);
//       }
//       return stringBuilder.toString();
//
//  }
  //方法2
    private String getBodyStr(HttpServletRequest request) throws IOException {

        InputStreamReader reader=new InputStreamReader(request.getInputStream());
         OutputStream outputStream=new OutputStreamWriter(reader);
        int line=0;
        StringBuilder stringBuilder=new StringBuilder();
        while ((line=reader.read())!=-1){
            stringBuilder.append((char) line);
           log.info("par="+(char)line);
        }
        return stringBuilder.toString();

    }
}

 

posted @ 2023-03-01 17:49  甜菜波波  阅读(618)  评论(0编辑  收藏  举报