Could not find acceptable representation 原因探究
日志信息
2022-06-15 19:48:23.399 WARN 2208 --- [p-nio-80-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]
日志是一条warn信息,但是下面的报错就是重新定向到/error路径了,因此可以断定项目出错的地方在这个warn类型日志上
概况
主要的功能是Excel文件下载,文件下载时设置MediaType
但是设置之后却会出现错误,项目内其他json类型MediaType
却可以正常返回不受影响,受影响的仅仅为下载接口。
分析
对代码进行debug,数据正常组装到ResponseEntity
但是在返回的时候Spring的返回类型MediaType
仅仅只有json类型。那么可能就时SpringBoot结果转换器出现问题。 查看以前覆写的WebMvcConfigurationSupport
当初为了支持Iong类型精度不丢失重写了结果转换器,当时仅考虑到json类型,对于其他类型忘记写了,因此埋下了隐患。
@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.QuoteFieldNames,
SerializerFeature.WriteEnumUsingToString,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.DisableCircularReferenceDetect);
fastJsonConfig.setSerializeFilters((ValueFilter) (o, s, source) -> {
if ((source instanceof Long || source instanceof BigInteger) && source.toString().length() > 15) {
return source.toString();
} else {
return null == source ? Constants.EMPTY : source;
}
});
//处理中文乱码问题
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastConverter.setSupportedMediaTypes(fastMediaTypes);
fastConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastConverter);
}
可以看出转换器中仅仅支持的MediaType为json-utf-8
类型那么。
解决方案
在上面的代码后面加上一下代码就可以,也就是新增一些转换器
converters.add(new ByteArrayHttpMessageConverter());
converters.add(new ResourceHttpMessageConverter());
converters.add(new SourceHttpMessageConverter());
converters.add(new AllEncompassingFormHttpMessageConverter());
HttpMessageConverter作用
以下为请求流程图
以下为返回流程图
请求和返回都需要有合适的消息转换器将不同类型(MediaType)的的消息如JSON
,XML
等转化为对应的格式
如请求来的时候@RequestBody注解就会使用json媒体类型。
而我们的错误也很明确,就是返回的类型仅仅为配置了fastjson类型,因此加上其他的转换器就可以解决这个问题。