当端点以文件名结尾时,我的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
设为true
或false
,但这只是一个疯狂的猜测什么有效:
/file/{fileName:.+}
更改为/file/{fileName:.+}/update
但这只是一种解决方法,而不是解决方案。重要:我正在使用Groovy并且我正在使用YML配置。
答案 0 :(得分:1)
一个选项是使用@RequestMapping options定义您的方法也使用json:
@RequestMapping(
value = "/file/{fileName:.+}",
method = RequestMethod.PUT,
produces = "application/json",
consumes = "application/json",
)
这可能会阻止您的应用程序尝试将数据转换为XML。
还要确保客户端正确设置“Content-Type”标头