Spring REST - 当URL以.xml结尾时,如何强制使用JSON作为响应类型

时间:2016-10-20 09:28:43

标签: spring groovy spring-restcontroller

当端点以文件名结尾时,我的Spring REST API出现问题(=> 406,例如: /file/example.xml因为它假设结果应该是XML,但那是错误的(它应该是JSON)。

Written [{timestamp=Thu Oct 20 11:11:14 CEST 2016, status=406, error=Not Acceptable, exception=org.springframework.web.HttpMediaTypeNotAcceptableException, message=Could not find acceptable representation, path=/file/foobar.xml}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@7015ebef]

我读了一些关于Spring 4功能检测文件扩展名并覆盖响应类型的内容,所以我尝试强制执行响应类型,但我找不到解决方案。

这是我的REST控制器:

@CompileStatic
@RestController
class ImportFileController {
    @RequestMapping(
            value = "/file/{fileName:.+}",
            method = RequestMethod.PUT,
            produces = "application/json"
    )
    @ResponseBody
    public ImportFile update(
            @PathVariable("fileName") String fileName,
            @RequestBody ImportFile importFile) {
        // ..
        return importFile
    }
}

这是请求/回复:

Request PUT /file/foobar.xml {"reader_name":"something"}
Response 406 {
  "timestamp" : "2016-10-20 08:56:35",
  "status" : 406,
  "error" : "Not Acceptable",
  "exception" : "org.springframework.web.HttpMediaTypeNotAcceptableException",
  "message" : "Could not find acceptable representation",
  "path" : "/file/foobar.xml"
}

我尝试了什么:

  • 使用{filenName:.+}代替{fileName}
  • produces
  • 中使用@RequestMapping
  • 发送自定义Accept标题(application/json
  • spring.mvc.path-matching.suffix-pattern设为truefalse,但这只是一个疯狂的猜测

什么有效:

  • 将端点从/file/{fileName:.+}更改为/file/{fileName:.+}/update 但这只是一种解决方法,而不是解决方案。

重要:我正在使用Groovy并且我正在使用YML配置。

1 个答案:

答案 0 :(得分:1)

一个选项是使用@RequestMapping options定义您的方法也使用json:

@RequestMapping(
            value = "/file/{fileName:.+}",
            method = RequestMethod.PUT,
            produces = "application/json",
            consumes = "application/json",
    )

这可能会阻止您的应用程序尝试将数据转换为XML。

还要确保客户端正确设置“Content-Type”标头