【发布时间】:2018-10-16 07:57:46
【问题描述】:
我正在尝试制作简单的 REST 服务,但遇到了 2 个问题。 1. REST控制器的任何方法都返回406 http错误;
@GetMapping(value = "/getUser/{id}", headers = "Accept=application/json",
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public ResponseEntity<Object> getUser(@PathVariable(value = "id")Long id) {
if (id == null) return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
UserInfo userInfo = userService.get(id);
if (userInfo == null) return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(userInfo, HttpStatus.OK);
}
@GetMapping(value = "/getUsers", headers = "Accept=application/json",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public List<UserInfo> getUsers()
{
return userService.getAll();
}
所以谷歌告诉我,这个问题可能在于缺少 Jackson2 依赖项。 但是添加此依赖项会导致此错误,添加较低版本会导致相同的输出或 406
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.4</version>
</dependency>
> 06-May-2018 15:36:45.477 WARNING [http-nio-25565-exec-3]
> org.springframework.context.support.AbstractApplicationContext.refresh
> Exception encountered during context initialization - cancelling
> refresh attempt:
> org.springframework.beans.factory.BeanCreationException: Error
> creating bean with name 'requestMappingHandlerAdapter' defined in
> class path resource
> [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]:
> Bean instantiation via factory method failed; nested exception is
> org.springframework.beans.BeanInstantiationException: Failed to
> instantiate
> [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]:
> Factory method 'requestMappingHandlerAdapter' threw exception; nested
> exception is java.lang.NoClassDefFoundError:
> com/fasterxml/jackson/databind/exc/InvalidDefinitionException
我做错了什么?
【问题讨论】:
-
什么时候得到406码?您是否尝试从浏览器访问?
-
这可能是由接受标头引起的,您不需要这样做,因为您没有在正文中发送任何内容。你也可以使用
consumes属性 -
@MạnhQuyếtNguyễn 是的
-
@zakariaamine 如果我尝试通过浏览器访问,我应该使用什么媒体类型?
-
consumes指的是方法或端点所期望的内容类型,而不是您收到的内容类型(例如浏览器)。您收到的内容由produces定义