【发布时间】:2015-05-13 01:35:41
【问题描述】:
我遇到了一个无条件的问题。我在 Spring Json 中创建了我的 REST 服务。我的服务假设可以使用“Content-Type application/json”,但是每当我提出没有 content-type 的请求时,它就会引发异常。
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported
但是我正在使用 @ExceptionHandler 处理此异常,但 spring 无法处理此异常,并且我的控件未进入 @ExceptionHandler 方法。
请指教!如何确保我的传入请求需要发送内容类型标头??
我想在我的@ExceptionHandler 方法中捕获这个异常,以便我可以发送带有错误代码的错误消息。
@RequestMapping(value = "/login", consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<ReponseWrapper> login(@Valid LoginRequest loginRequest,
BindingResult results,) {
//any code
}
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
@ResponseStatus(value = HttpStatus.UNSUPPORTED_MEDIA_TYPE)
public @ResponseBody Map<String, Object> handleUnsupportedMediaTypeException(HttpMediaTypeNotSupportedException ex) throws IOException {
Map<String, Object> map = Maps.newHashMap();
map.put("error", "Unsupported Media Type");
map.put("cause", ex.getLocalizedMessage());
map.put("supported", ex.getSupportedMediaTypes());
return map;
}
【问题讨论】:
-
试试
produces = "application/json;charset=UTF-8"而不是consumes = MediaType.APPLICATION_JSON -
您是否在应用程序上下文中配置了任何异常解析器?
-
您可以在请求到达控制器之前使用过滤器来验证请求,并检查内容类型以避免此类请求可能是其中一种方式。也许您可以尝试这种方法
标签: java json spring rest spring-mvc