【发布时间】:2021-12-02 21:10:12
【问题描述】:
我的 Spring 应用程序配置为使用 GET 参数进行内容协商。代码是 Kotlin,但在 Java 中也一样。
配置:
override fun configureContentNegotiation(configurer: ContentNegotiationConfigurer) {
configurer.favorParameter(true)
.parameterName("format")
.ignoreAcceptHeader(false)
.defaultContentType(MediaType.APPLICATION_JSON)
.mediaType("text/plain", MediaType.TEXT_PLAIN)
.mediaType("application/json", MediaType.APPLICATION_JSON)
.mediaType("application/rdf+xml", MediaType("application", "rdf+xml"))
}
以及以下控制器方法:
@GetMapping("/test", produces=["text/plain"])
fun testText() : String {
return "Hello"
}
@GetMapping("/test", produces=["application/json"])
fun testJson() : Map<String, String> {
return mapOf("hello" to "world")
}
@GetMapping("/test", produces=["application/rdf+xml"])
fun testRdf(response: HttpServletResponse) {
// dummy response, to demonstrate using output stream.
response.setContentType("application/rdf+xml")
response.outputStream.write("dummy data".toByteArray())
response.outputStream.close()
}
testRdf 返回void 并使用输出流将正文数据发回。
以下工作正常:
-
http://localhost:8080/test?format=text/plain给了我纯文本 -
http://localhost:8080/test?format=application/json给了我 JSON
但是http://localhost:8080/test?format=application/rdf+xml 给了我一个 HTTP 406 并且日志说
org.apache.tomcat.util.http.Parameters : Start processing with input [format=application/rdf+xml]
o.s.web.servlet.DispatcherServlet : GET "/test?format=application/rdf+xml", parameters={masked}
.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]
o.s.web.servlet.DispatcherServlet : Completed 406 NOT_ACCEPTABLE
调试器显示它甚至没有调用我的函数。
(为了证明 testRdf 处理程序符合预期,我将路径设为唯一并删除了 produces 注释 - 它在内容协商之外工作正常并按预期返回正文。)
据我所知,我已经表明我的方法是该内容类型的正确处理程序,并且我已经正确注册了该内容类型。
为什么 Spring 不认为我的处理程序满足内容协商请求?
【问题讨论】:
标签: spring spring-mvc content-negotiation