HttpServletRequest.getInputStream()多次读取问题

2023年7月20日10:06:34

HttpServletRequest.getInputStream()多次读取问题

我们放在body里的数据
HttpServletRequest.getInputStream()多次读取问题
我们有时候通过HttpServletRequest.getInputStream()读取body里的数据

 private String getBody(HttpServletRequest request) throws IOException {
    InputStream in = request.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")));
    StringBuffer sb = new StringBuffer("");
    String temp;
    while ((temp = br.readLine()) != null) {
        sb.append(temp);
    }
    if (in != null) {
        in.close();
    }
    if (br != null) {
        br.close();
    }
    return sb.toString();
}

注意,这里有了一次request.getInputStream()调用。

但是在测试时,一直报JSON格式不正确的错误。经调查发现,项目中使用了公司基础组件中的Filter,而该Filter中也解析了body。同时,不出所料,也是通过调用getInputStream()方法获取的。

原来:

  • 一个InputStream对象在被读取完成后,将无法被再次读取,始终返回-1;
  • InputStream并没有实现reset方法(可以重置首次读取的位置),无法实现重置操作;

因此,当自己写的Filter中调用了一次getInputStream()后,后面再调用getInputStream()读取的数据都为空,所以才报JSON格式不正确的错误。

注意:@RequestBody 和 @RequestParam 都不能配合request.getInputStream()使用,因为@RequestBody 和 @RequestParam也是读取body里数据
参考:HttpServletRequest中读取HTTP请求的body

  • 作者:小白升职记
  • 原文链接:https://blog.csdn.net/qq_41604383/article/details/108253697
    更新时间:2023年7月20日10:06:34 ,共 911 字。