首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >Spring莫名其妙地抛出HttpMediaTypeNotAcceptableException

Spring莫名其妙地抛出HttpMediaTypeNotAcceptableException
EN

Stack Overflow用户
提问于 2021-12-02 21:10:12
回答 1查看 99关注 0票数 0

我的Spring应用程序配置为使用GET参数进行内容协商。代码是Kotlin,但在Java中也是如此。

配置:

代码语言:javascript
运行
复制
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"))
    }

以及下列控制器方法:

代码语言:javascript
运行
复制
@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给我普通的text
  • http://localhost:8080/test?format=application/json给我JSON

但是http://localhost:8080/test?format=application/rdf+xml给了我一个HTTP406,日志显示

代码语言:javascript
运行
复制
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不考虑我的处理程序满足内容协商请求?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-03 07:37:29

我找到了答案。需要对URL进行编码的参数字符,因此可以很好地工作:

代码语言:javascript
运行
复制
http://localhost:8080/test?format=application%2Frdf%2Bxml
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70206482

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档