package com.example.config.request.resulet;
import com.example.config.exception.handler.BusinessException;
import com.example.config.response.enums.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import org.apache.commons.io.IOUtils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
@Slf4j
@Component
// 记得修改为自己的包名
@ControllerAdvice(basePackages = "com.example")
public class RequestResulet implements RequestBodyAdvice {
@Override
public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
return true;
}
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
try{
// 将流转为字符串方便查看
String requestBody = IOUtils.toString(httpInputMessage.getBody());
// 这儿可以做自己想做的事,加密解密
log.info(requestBody);
return new HttpInputMessage() {
@Override
public HttpHeaders getHeaders() {
return httpInputMessage.getHeaders();
}
@Override
public InputStream getBody() throws IOException {
return new ByteArrayInputStream(requestBody.getBytes(StandardCharsets.UTF_8));
}
};
}catch (Exception e){
throw new BusinessException(ResultCode.PARAM_IS_INVALID);
}
}
@Override
public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
Method method=methodParameter.getMethod();
log.info("{}.{}:{}",method.getDeclaringClass().getSimpleName(),method.getName());
return o;
}
@Override
public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
Method method=methodParameter.getMethod();
log.info("{}.{}",method.getDeclaringClass().getSimpleName(),method.getName());
return o;
}
}
spring boot 请求数据加密解密
最新推荐文章于 2023-11-17 16:33:57 发布