【spring boot】在自定义拦截器中从request中获取json字符串

时间:2023-03-09 02:56:25
【spring boot】在自定义拦截器中从request中获取json字符串

又这样的需求,需要在自定义的拦截器中获取request中的数据,想获取到的是JSON字符串

那需要在拦截器中写这样一个方法

public static String getOpenApiRequestData(HttpServletRequest request){
try { int contentLength = request.getContentLength();
if (contentLength < 0) {
return null;
}
byte buffer[] = new byte[contentLength];
for (int i = 0; i < contentLength;) { int readlen = request.getInputStream().read(buffer, i, contentLength - i);
if (readlen == -1) {
break;
}
i += readlen;
} String charEncoding = request.getCharacterEncoding();
if (charEncoding == null) {
charEncoding = "UTF-8";
}
return new String(buffer, charEncoding); } catch (Exception e) {
e.printStackTrace();
} return null;
}

然后在拦截器的preHandle方法中,调用就拿到了String字符串,然后自己JSON序列化一下

JSONObject jsonObject1 = JSON.parseObject(OpenApiInterceptor.getOpenApiRequestData(httpServletRequest));

即可得到!