【问题标题】:@PathVariable fileName results to 406 Not Acceptable@PathVariable fileName 结果为 406 Not Acceptable
【发布时间】:2018-07-31 10:43:29
【问题描述】:

我有一个像下面这样的处理方法,它需要 fileName

@GetMapping(value = ["/test/{fileName:.+}"], produces = [(MediaType.APPLICATION_JSON_VALUE)])
fun getFile(@PathVariable fileName: String): ResponseEntity<Map<String, String>> {
    return ResponseEntity.ok(hashMapOf(Pair("fileName", fileName)))
}

我遇到了一些奇怪的行为,即

  • 调用/test/item-1.exx结果到{"fileName": "item-1.exx"}
  • 调用/test/item-1.855 结果到{"fileName": "item-1.855"}
  • 调用/test/item-1.pn8 结果到{"fileName": "item-1.pn8"}

但如果我尝试使用有效扩展名调用该方法,我会得到 406 Not Acceptable

  • 调用/test/item-1.png结果到406 Not Acceptable
  • 调用/test/item-1.jpg结果到406 Not Acceptable
  • 调用/test/item-1.exe结果到406 Not Acceptable

我得到以下异常

org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

如何解决这个问题?我希望能够使用有效的扩展名调用该方法。

【问题讨论】:

  • 使用 Spring Boot 1.5.9.RELEASE

标签: java spring spring-mvc spring-boot kotlin


【解决方案1】:

这是因为内容协商,只要尝试在请求头中添加Content-Type,应该可以解决这个问题,或者禁用内容协商。看看这个链接:https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc

【讨论】:

    【解决方案2】:

    @Jaiwo99 的回答给了我关于需要做什么的提示。这是我找到的解决方案。

    解决方案 1:配置 ContentNegotiation

    @Bean
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
                configurer
                    .useJaf(false)
                    .defaultContentType(MediaType.APPLICATION_JSON);
            }
        };
    }
    

    解决方案 2:编辑 application.yml / application.properties

    spring:
        mvc:
            media-types:
                png: application/json
                jpg: application/json
                jpeg: application/json
    

    【讨论】:

      猜你喜欢
      • 2017-05-25
      • 1970-01-01
      • 2013-08-10
      • 2016-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-21
      • 2014-11-12
      相关资源
      最近更新 更多