从HttpServletRequest获取POST请求体

2022/7/23 23:25:18

本文主要是介绍从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获取POST请求体的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程