拦截器获取HttpServletRequest里body数据
时间: 2023-07-27 14:29:35 浏览: 188
在拦截器中获取HttpServletRequest里的body数据可以通过以下步骤实现:
1. 在拦截器的preHandle()方法中获取HttpServletRequest对象,代码如下:
```java
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
```
2. 通过HttpServletRequest对象获取输入流InputStream,代码如下:
```java
InputStream inputStream = request.getInputStream();
```
3. 将输入流InputStream转换为字符串String,代码如下:
```java
String body = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
```
这里使用了IOUtils类,需要导入相关依赖。
完整代码示例:
```java
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
InputStream inputStream = request.getInputStream();
String body = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
System.out.println("请求body数据:" + body);
return true;
}
}
```
阅读全文