栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Could not find acceptable representation 原因探究

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Could not find acceptable representation 原因探究

Could not find acceptable representation 原因探究

文章目录
  • Could not find acceptable representation 原因探究
    • 日志信息
    • 概况
    • 分析
    • 解决方案
    • HttpMessageConverter作用

日志信息
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> 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 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类型,因此加上其他的转换器就可以解决这个问题。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/981619.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号