【问题标题】:Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing无法读取 HTTP 消息:org.springframework.http.converter.HttpMessageNotReadableException:缺少所需的请求正文
【发布时间】:2016-06-03 14:35:12
【问题描述】:

我有拦截器,由于某些原因,我必须像这样阅读HttpServletRequest 中包含的发布日期:

    InputStream 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("");
    }

执行此操作后,我收到 400 个错误的 ajax 请求 读取 HTTP 消息失败:org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing

【问题讨论】:

    标签: spring interceptor


    【解决方案1】:

    我猜你有一个方法处理程序,如下所示:

    @RequestMapping(value = "/somewhere", method = POST)
    public SomeResponse someHandler(@RequestBody String body, ...) { ... }
    

    然后您在拦截器中读取了HttpServletRequest 的InputStream。由于您只能读取一次InputStream,因此当spring 尝试读取InputStream 以填充@RequestBody 方法参数时,它会失败并报错HttpMessageNotReadableException。

    如果你真的需要多次读取请求体,你应该添加一个过滤器并装饰HttpServletRequest以添加一个Multiple Read功能。有关更多信息,您可以阅读此answer。

    【讨论】:

    • 这是真的。我将其更改为过滤器。它很好,但它将内容更改为非 unicode。这个呢?
    • 覆盖过滤器中的getCharacterEncoding 方法以将UTF-8 作为字符编码返回
    【解决方案2】:

    Spring 提供了一个名为ContentCachingRequestWrapper 的类,它扩展了HttpServletRequestWrapper。此类缓存从读取的所有内容 getInputStream() 和 getReader() 并允许通过 getContentAsByteArray() 检索此内容。因此我们可以为此目的多次检索InputStream。 ContentCachingRequestWrapper 中的方法提供的这种能力:

     @Override
       public ServletInputStream getInputStream() throws IOException {
            if (this.inputStream == null) {
                this.inputStream = new ContentCachingInputStream(getRequest().getInputStream());
            }
            return this.inputStream;
        }
    

    此类修复UTF-8 的字符编码问题,方法如下:

    @Override
    public String getCharacterEncoding() {
        String enc = super.getCharacterEncoding();
        return (enc != null ? enc : WebUtils.DEFAULT_CHARACTER_ENCODING);
    }
    

    Here 是ContentCachingRequestWrapper 中的完整详细信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-09
      • 1970-01-01
      • 2017-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多