坑记(HttpInputMessage)

一、背景知识

public interface HttpInputMessage
extends HttpMessage
Represents an HTTP input message, consisting of headers and a readable body.

Typically implemented by an HTTP request on the server-side, or a response on the client-side.

Since:
3.0
Author:
Arjen Poutsma

在实现接口的加密处理过程中, 我们一般选择使用SpringMVCResponseBodyRequestBody,实现接口报文的监听和处理操作。在监听时,需分别实现相关的Advice类,以帮助完成自己的逻辑实现。交互流程图可以参考:
在这里插入图片描述

HttpInputMessage正是我们需要获取header和请求body的关键。今天我们谈谈使用过程中可能遇到的问题。

二、情况说明

1. 问题描述

我们在实现RequestBodyAdvice时,通常会重写以下方法:

 public HttpInputMessage beforeBodyRead(final HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
      //读取请求body
      byte[] body = new byte[inputMessage.getBody().available()];
      inputMessage.getBody().read(body);
}

如我们使用以上方式,读取请求报文数据时,可能产生“读不完整”的现象。因为InputStream .available()方法描述如下:

public abstract class InputStream implements Closeable {
/**
     * Returns an estimate of the number of bytes that can be read (or
     * skipped over) from this input stream without blocking by the next
     * invocation of a method for this input stream. The next invocation
     * might be the same thread or another thread.  A single read or skip of this
     * many bytes will not block, but may read or skip fewer bytes.
     *
     * <p> Note that while some implementations of {@code InputStream} will return
     * the total number of bytes in the stream, many will not.  It is
     * never correct to use the return value of this method to allocate
     * a buffer intended to hold all data in this stream.
     *
     * <p> A subclass' implementation of this method may choose to throw an
     * {@link IOException} if this input stream has been closed by
     * invoking the {@link #close()} method.
     *
     * <p> The {@code available} method for class {@code InputStream} always
     * returns {@code 0}.
     *
     * <p> This method should be overridden by subclasses.
     *
     * @return     an estimate of the number of bytes that can be read (or skipped
     *             over) from this input stream without blocking or {@code 0} when
     *             it reaches the end of the input stream.
     * @exception  IOException if an I/O error occurs.
     */
    public int available() throws IOException {
        return 0;
    }
}

其中,有一句描述:

many bytes will not block, but may read or skip fewer bytes.

这就厉害了,不阻塞,但是可能丢包…所以如果使用上述方法,读取请求body时,数据并不完整,会导致后续逻辑出现异常。

2. 解决过程

上述方法有问题,可使用这个办法:

String reqBody = StreamUtils.copyToString(inputMessage.getBody(), Charset.defaultCharset());

亲测有效哦~

结束语

多看、多学、多试,总会找到解决的办法和途径。

  • 12
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在Spring框架中,如果我们想要对一个GET请求的请求体进行处理,则可以通过实现`RequestBodyAdvice`接口来实现。 `RequestBodyAdvice`接口有四个方法: 1. `supports(MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType)`:用于判断支持哪些请求体的处理。如果返回`true`,则会调用后面三个方法对请求体进行处理;否则不会进行处理。 2. `beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType)`:在请求体读取之前调用,用于对请求体进行处理。 3. `afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType)`:在请求体读取之后调用,用于对请求体进行处理。 4. `handleError(HttpMessageNotReadableException ex, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType)`:在读取请求体出现异常时调用。 需要注意的是,`RequestBodyAdvice`只对请求体为JSON格式的GET请求有效,对于其他格式的请求体(如form-data),需要使用其他方式进行处理。 以下是一个使用`RequestBodyAdvice`处理请求体的示例: ```java @ControllerAdvice public class CustomRequestBodyAdvice implements RequestBodyAdvice { @Override public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) { return methodParameter.getMethod().getName().equals("getUserInfo") && type.equals(UserInfo.class); } @Override public Object beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException, HttpMessageNotReadableException { String requestBody = StreamUtils.copyToString(httpInputMessage.getBody(), StandardCharsets.UTF_8); JSONObject jsonObject = JSON.parseObject(requestBody); UserInfo userInfo = new UserInfo(); userInfo.setUserName(jsonObject.getString("userName")); userInfo.setPassword(jsonObject.getString("password")); return userInfo; } @Override public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) { return o; } @Override public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) { return o; } @Override public void handleError(HttpMessageNotReadableException httpMessageNotReadableException, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException { throw httpMessageNotReadableException; } } ``` 在以上示例中,我们使用`supports`方法判断请求体是否为`UserInfo`类型,如果是则调用`beforeBodyRead`方法对请求体进行处理,将JSON格式的请求体转换成`UserInfo`对象。最后,我们返回处理后的`UserInfo`对象即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值