HttpMediaTypeNotAcceptableException:中找不到的Exception

2019-05-12 02:10发布

我在我的控制器(春季4.1)以下图像下载方式:

@RequestMapping(value = "/get/image/{id}/{fileName}", method=RequestMethod.GET)
public @ResponseBody byte[] showImageOnId(@PathVariable("id") String id, @PathVariable("fileName") String fileName) {
    setContentType(fileName); //sets contenttype based on extention of file
    return getImage(id, fileName);
}

下面ControllerAdvice方法应该处理不存在的文件,并返回一个JSON错误响应:

@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public @ResponseBody Map<String, String> handleResourceNotFoundException(ResourceNotFoundException e) {
    Map<String, String> errorMap = new HashMap<String, String>();
    errorMap.put("error", e.getMessage());
    return errorMap;
}

我的JUnit测试工作完美无瑕

编辑这是因为extention .bla的:这也适用于应用服务器):

@Test
public void testResourceNotFound() throws Exception {
    String fileName = "bla.bla";
      mvc.perform(MockMvcRequestBuilders.get("/get/image/bla/" + fileName)
            .with(httpBasic("test", "test")))
            .andDo(print())
            .andExpect(jsonPath("$error").value(Matchers.startsWith("Resource not found")))
            .andExpect(status().is(404));
}

并给出了下面的输出:

MockHttpServletResponse:
          Status = 404
   Error message = null
         Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY], Content-Type=[application/json]}
    Content type = application/json
            Body = {"error":"Resource not found: bla/bla.bla"}
   Forwarded URL = null
  Redirected URL = null
         Cookies = []

但是在我的应用程序服务器,我得到试图donwload不存在的图像时出现以下错误信息:

(EDIT这是因为extention .JPG的:这也失败于JUnit测试以.jpg extention):

ERROR org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Failed to invoke @ExceptionHandler method: public java.util.Map<java.lang.String, java.lang.String> nl.krocket.ocr.web.controller.ExceptionController.handleResourceNotFoundException(nl.krocket.ocr.web.backing.ResourceNotFoundException) org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

我在我的MVC配置中配置了MessageConverter如下:

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(mappingJackson2HttpMessageConverter());
    converters.add(byteArrayHttpMessageConverter());
}

@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    //objectMapper.registerModule(new JSR310Module());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(objectMapper);
    converter.setSupportedMediaTypes(getJsonMediaTypes());
    return converter;
}

@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
    ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
    arrayHttpMessageConverter.setSupportedMediaTypes(getImageMediaTypes());
    return arrayHttpMessageConverter;
}

我在想什么? 为什么是JUnit测试工作?

Answer 1:

您需要决定如何响应的媒体类型应该由Spring来确定。 这可以通过多种方式来实现:

  • 路径扩展(例如/image.jpg)
  • URL参数(例如?格式= JPG)
  • HTTP Accept报头(例如接受:图像/ JPG)

默认情况下,春季着眼于延伸 ,而不是Accept头。 如果实施这种行为是可以改变的@Configuration扩展类WebMvcConfigurerAdapter 。 在那里,你可以重写configureContentNegotiation(ContentNegotiationConfigurer configurer) ,并配置配置者,以您的需求,如。 通过调用

ContentNegotiationConfigurer#favorParameter
ContentNegotiationConfigurer#favorPathExtension

如果同时设置到false ,那么Spring将着眼于Accept头。 由于您的客户端可以说Accept: image/*,application/json和同时处理,春季应能返回任何图像或错误JSON。

请参见本教程春季对内容协商的更多信息和示例。



Answer 2:

注意你的HTTP Accept头。 例如,如果你的控制器产生“应用/八位字节流”(响应),您的Accept报头不应该被“应用程序/ JSON”(在请求):

@GetMapping(value = "/download", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void download(HttpServletResponse response) {}


文章来源: HttpMediaTypeNotAcceptableException: Could not find acceptable representation in exceptionhandler