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

Spring REST消耗导致HTTP状态406-不可接受,spring,rest,http-status-code-406,Spring,Rest,Http Status Code 406,我在尝试使用REST 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

我在尝试使用REST 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:header时得到了这个答案。我试图请求一个image/jpeg,但我的请求包含“Accept:application/json”


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

将此添加到spring mvc dispatcher:

<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>


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

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

此外,您可以修复add“Accept”、“/”


对不起,我是科特林

你说得对,谢谢!我已经更改了它,但现在出现以下错误:“HTTP状态405-请求方法'get'不受支持”。为什么会发生这种情况?看起来控制器的方法不再映射了。我不知道为什么。它现在起作用了,这里有一个总结:-确保你已经添加了jackson库(客户端和服务器端)-不管是“=”还是“:”是写的-现在已经添加了jackson库-一切正常。
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)