HttpMediaTypeNotAcceptableException: Could not find acceptable representation in exceptionhandler

前端 未结 2 457
梦如初夏
梦如初夏 2020-12-01 18:27

I have the following image download method in my controller (Spring 4.1):

@RequestMapping(value = \"/get/image/{id}/{fileName}\", method=RequestMethod.GET)
p         


        
相关标签:
2条回答
  • 2020-12-01 18:56

    Pay attention to your HTTP Accept header. For example, if your controller produces "application/octet-stream" (in response), your Accept header should NOT be "application/json" (in request):

    @GetMapping(value = "/download", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void download(HttpServletResponse response) {}
    
    0 讨论(0)
  • 2020-12-01 19:05

    You need to decide how the media type of the response should be determined by Spring. That can be done in several ways:

    • path extension (eg. /image.jpg)
    • URL parameter (eg. ?format=jpg)
    • HTTP Accept header (eg. Accept: image/jpg)

    By default, Spring looks at the extension rather than the Accept header. This behaviour can be changed if you implement a @Configuration class that extends WebMvcConfigurerAdapter (or since Spring 5.0 simply implement WebMvcConfigurer. There you can override configureContentNegotiation(ContentNegotiationConfigurer configurer) and configure the ContentNegotiationConfigurer to your needs, eg. by calling

    ContentNegotiationConfigurer#favorParameter
    ContentNegotiationConfigurer#favorPathExtension
    

    If you set both to false, then Spring will look at the Accept header. Since your client can say Accept: image/*,application/json and handle both, Spring should be able to return either the image or the error JSON.

    See this Spring tutorial on content negotiation for more information and examples.

    0 讨论(0)
提交回复
热议问题