菜鸟笔记
提升您的技术认知

Http状态码406(Not Acceptable) 错误问题解决方法

状态码406:HTTP协议状态码的一种(4xx表示客户端的问题),表示客户端无法解析服务端返回的内容。说白了就是后台的返回结果前台无法解析就报406错误。

示例代码中请求代码,后台代码均正常,且有返回信息。如下图:

$.ajax({
            url:'http://localhost:8080/findDsrwByDsrwid',
            type : 'post',
            data :{
                id : cztj
            },
            dataType:'json',
        }).success(function(result){
          }

那我们来看看网页状态:

状态码:406,请求头(Request Headers)中看到Accept优先是application/json格式,而响应头(Response Hraders)中却发现返回信息的格式是“text/html”,前台无法解析,需将结果转换成json格式返回给前台。

解决方案:

jackson开源工具(springmvC天然支持)

导入jackson-core和jackson-mapper-asl的依赖包,如果你是maven工程,在pom加入

 <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.1.4</version>
    </dependency>

      <!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl -->
      <dependency>
          <groupId>org.codehaus.jackson</groupId>
          <artifactId>jackson-mapper-asl</artifactId>
          <version>1.9.12</version>
      </dependency>

此时还需要关注springMVC的一个配置,具体原因请看原理解析。

原理解析:

为什么只要导入jar就好了呢?是因为spring mvc 配置了 <mvc:annotation-driver/> 后 ,如果classpath 里面包含jackson 包,则自动注册MappingJackson2HttpMessageConverter,从而支持json 输出。

这是springMVC中的一句配置

<!-- 能支持springmvc更高级的一些功能,JSR303,快捷的ajax -->
<mvc:annotation-driven/>

且annotation-driver是被AnnotationDrivenBeanDefinitionParser解析,这里提供另外一篇博文,希望有所帮助。

spring mvc jackson 支持原理分析_taotoxht的专栏-CSDN博客_jackson 原理

结果展示:

————————————————————————————————————————————————————

2020.01.30:,今天搭了另外一个项目的环境,项目依赖中已有jackson-annotations-*.jar,jackson-core-.jar,jackson-databind-.jar 包,打开注解驱动<mvc:annotation-driven>依然报406,如果有同学试了以上方案不行的话,可以试着尝试fastjson替代jackson,具体是:

引入jar包:

        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>

注解驱动<mvc:annotation-driven>配置为:

	<mvc:annotation-driven>
		<mvc:message-converters register-defaults="true">
			<!-- 配置Fastjson支持 -->
			<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
				<property name="supportedMediaTypes">
					<list>
						<value>application/json</value>
						<value>text/html;charset=UTF-8</value>
					</list>
				</property>
<!--				<property name="features">
					<list>
						<value>WriteMapNullValue</value>
						<value>QuoteFieldNames</value>
					</list>
				</property>-->
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>

结果: