其他分享
首页 > 其他分享> > 从HttpServletRequest获取POST请求体

从HttpServletRequest获取POST请求体

作者:互联网

从HttpServletRequest获取POST请求体

注意

使用以下方式读取时可能会出现getInputStream() has already been called for this request报错信息( HttpServletRequest 流数据不可重复读)

出现原因:

  • 不能和@Requestbody搭配使用
  • 如果你的项目中有在过滤器中对post请求体作过处理,比如取出post的body进行MD5,以校验是否重复提交

第一种方式

StringBuffer data = new StringBuffer();
        String line = null;
        BufferedReader reader = null;
        reader = request.getReader();
        while (null != (line = reader.readLine())) {
            data.append(line);
        }
jsonSt = data.toString();

第二种方式

String jsonSt = null; 
if ("POST".equalsIgnoreCase(request.getMethod())) {
            jsonSt = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        }

测试代码

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 从HttpServletRequest获取POST请求体
 *
 * @author lyn
 * @date 2022/7/21 18:17
 */
@RestController
public class RequestController {

    @PostMapping("/request1")
    public String request1(HttpServletRequest request) throws IOException {

        StringBuffer data = new StringBuffer();
        String line = null;
        BufferedReader reader = null;
        reader = request.getReader();
        while (null != (line = reader.readLine())) {
            data.append(line);
        }
        return data.toString();
    }

    @PostMapping("/request2")
    public String request2(HttpServletRequest request) throws IOException {

        if ("POST".equalsIgnoreCase(request.getMethod())) {
            return request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        }
        return "";
    }

    /**
     * 不能和@Requestbody搭配使用
     * 原因: getInputStream() has already been called for this request,流不能读取第二次
     * ,@Requestbody已经读取过一次了
     *
     * @param paramMap
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/request3")
    public String request3(@RequestBody Map<String, Object> paramMap, HttpServletRequest request) throws IOException {

        if ("POST".equalsIgnoreCase(request.getMethod())) {
            return request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        }
        return "";
    }

}

结果示例

01

image-20220723222920852

02

image-20220723223006924

03

image-20220723223049008

标签:HttpServletRequest,return,请求,request,import,POST,null
来源: https://www.cnblogs.com/lyn8100/p/16513513.html