Spring Boot返回图片接口参数校验抛HttpMediaTypeNotAcceptableException如何解决
问题根因
你当前接口的@PostMapping注解上配置了produces = MediaType.IMAGE_PNG_VALUE,明确声明该接口仅会返回PNG图片类型的响应。但参数校验触发异常时,全局异常处理器返回的是JSON格式的自定义错误对象,Spring MVC找不到可以将JSON结构序列化为image/png类型的消息转换器,因此抛出了HttpMediaTypeNotAcceptableException异常。
修复方案
可以任选以下任意一种方案解决:
方案1:调整接口支持的响应类型(最简便)
修改接口的produces属性,新增JSON类型支持,让接口可以同时返回图片和JSON格式的响应:
@PostMapping(value = "/dummy", produces = {MediaType.IMAGE_PNG_VALUE, MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<BufferedImage> generateQRCode(@Valid @RequestBody CodeRequest paymentRequest) throws Exception { // 原有逻辑不变 }
方案2:异常响应显式指定Content-Type
在全局异常处理器构造返回值时,手动设置响应头的Content-Type为JSON类型,强制异常响应按JSON序列化:
@Override public ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException exception, HttpHeaders headers, HttpStatus status, WebRequest request) { log.error(exception.getMessage(), exception); ExceptionResponse exceptionResponse = new ExceptionResponse(HttpStatus.BAD_REQUEST, exception.getBindingResult().getAllErrors().get(0).getDefaultMessage()); // 新增:指定异常响应的Content-Type为JSON HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.APPLICATION_JSON); return new ResponseEntity<>(exceptionResponse, responseHeaders, exceptionResponse.getHttpStatus()); }
验证注意事项
用Swagger测试时,确保请求的Accept头包含application/json或者设置为*/*即可正常看到错误提示。
内容的提问来源于stack exchange,提问作者user1999453
相关产品推荐
相关产品推荐

