Spring REST消耗导致HTTP状态406-不可接受



当我尝试使用RESTneneneba API时,会出现此错误:

Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 406 Not Acceptable

以下是执行的客户端代码:

public static void main(String[] args) {
   Car c = getCarById(4);
   System.out.println(c);
}
public static  @ResponseBody Car getCarById(int id){
    return new RestTemplate().getForObject("http://localhost:8080/rest/cars/{id}", Car.class, id);
}

这是映射请求的控制器的代码:

@RequestMapping(value="/cars/{id}", method=RequestMethod.GET, headers = {"Accept=text/html,application/xhtml+xml,application/xml"}, produces="application/xml")
public @ResponseBody Car getCarById(@PathVariable("id") int id){
    return carService.getCarById(id);
}

尽管映射器应该负责映射到正确的类型,但为什么会出现这种错误(406不可接受)?

您发送的是Accept=标头,而不是Accept:标头。

当我的请求中有一个错误的Accept:头时,我得到了这个答案。我试图请求一个图像/jpeg,但我的请求包含"Accept:application/json"。

解决方案是使用正确的实体类进行查询(我查询Object只是为了看看会发生什么),在我的例子中是Resource.class.

将其添加到springmvc调度器:

<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- JSON format support for Exception -->
<bean id="methodHandlerExceptionResolver"
      class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
        </list>
    </property>
</bean>

在我的案例中,我不是在服务器端而是在客户端解决了这个问题。我使用Postman,得到406错误。但使用浏览器可以很好地处理请求。因此,我查看了浏览器中的请求标头,并在Postman中添加了Accept标头,如下所示:Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

此外,您可以修复添加"Accept"、"/"

val headers = HttpHeaders()
headers.add("Accept", "*/*")
val httpEntity = HttpEntity("parameters", headers)
restTemplate.exchange(....)
restTemplate.exchange("http://localhost:" + serverPort + "/product/1",
            HttpMethod.GET,
            httpEntity,
            String.javaClass)

对不起,是Kotlin

由于ContentType&接受通过为两者设置相同的字符串值解决了问题。

HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.valueOf(CONTENT_TYPE));
httpHeaders.setAccept(Arrays.asList(MediaType.valueOf(CONTENT_TYPE)));

我也遇到过同样的问题,最后是一个库问题。如果您不使用maven,您必须确保您已经包含json核心库及其所有依赖项。如果您的方法以json格式加载了输入参数,而您没有这些库,则会出现415错误。我认为这两个错误有着相同的根源:不完整的库。

相关内容

最新更新