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

ndr*_*zza 6 rest spring http-status-code-406

当我尝试使用 REST API 时出现此错误:

Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 406 Not Acceptable
Run Code Online (Sandbox Code Playgroud)

这是执行的客户端代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

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

@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);
}
Run Code Online (Sandbox Code Playgroud)

尽管映射器应该负责映射到正确的类型,但为什么会发生此错误(406-Not Acceptable)?

Tom*_*rdt 8

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

  • 它现在可以工作了,这里有一个总结: - 确保您添加了 **jackson 库**(客户端和服务器端) - 写入“=”或“:”并不重要 (4认同)