在我现有的一个API调用中引入ReaderInterceptor后,我收到422错误 . 之前调用工作正常,但在我介绍ReaderInterceptor后开始给出422 .
这是我的ReaderInterceptor的 aroundReadForm()
方法的代码
@Override
public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException {
InputStream is = context.getInputStream();
String body = new BufferedReader(new InputStreamReader(is)).lines().collect(Collectors.joining("\n"));
ObjectMapper mapper = new ObjectMapper();
try {
SampleObject sampleObject = mapper.readValue(body, SampleObject.class);
LOGGER.info(sampleObject.getSampleProperty());
} catch (JsonGenerationException | JsonMappingException e) {
LOGGER.info(e.getMessage());
}
return context.proceed();
}
我想要做的是在请求中读取正文,使用Jackson的 ObjectMapper
将其转换为POJO然后按原样移动请求 . 不确定,这个422状态代码的原因是什么 .
1 回答
ObjectMapper将关闭请求输入流 . 尝试从body变量创建一个新流 . 并调用context.setInputStream() .
你要做的事情的缺点是表现 . 似乎你会将JSON字符串解析为对象两次 . 一旦进入拦截器,一次进入阅读器 .
如果身体很小,这不是什么大问题 .
资源:https://www.baeldung.com/jersey-filters-interceptors