gpt4 book ai didi

java - MVC - 当内容类型是自定义的(不是应用程序/json)时接受 JSON

转载 作者:行者123 更新时间:2023-12-01 11:43:22 24 4
gpt4 key购买 nike

我正在尝试为我的网站实现 Content-Security-Policy-Report-Only header 。
为了做到这一点,我需要一个 Controller 来接受浏览器的 POST 请求——它将以 JSON 的形式发送有关违规的数据。然而,这个请求似乎将 Content-Type 指定为 application/csp-report而不是 application/json (旁注:为什么是 hell ??)。

这显然导致 Spring 拒绝请求 - 似乎是 @RequestBody 的用法。让 spring 只接受 Content-Type "application/json" 的请求.
即使我专门设置了值 consumes@RequestMapping注释到 application/csp-report它仍然不接受请求。

我已经使用过滤器用 HttpServletRequestWrapper 包装请求- 这似乎是修改请求行为的常用方法。
我已经覆盖了所有这些方法:getContentType() , getHeader(String) , getHeaders(String)返回“应用程序/json”。
但是请求仍然没有通过。

  • 我在这里缺少什么?
  • 有没有更好的解决方案
    不需要我对请求施展魔法?
  • 我什至不会
    介意手动解析 JSON,我能以某种方式接受它吗?
    字符串代替?
  • 最佳答案

    根据 @RequestBody 上的文档注解,

    The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request



    这意味着 Spring Framework 定义了一个专门的 API,用于定义在用作 REST 端点的参数时如何将某些 MediaType 转换为某些 Java 类型。

    Here是一篇很好的文章,展示了这些功能。

    如果您的媒体格式可以映射到它们各自的媒体格式,那么您可以配置和使用大量内置的 Spring 转换器。专门针对您的情况,您应该查看 spring.converter.json 中可用的转换器之一。包裹。在最简单的情况下,让它工作应该很简单:
    HttpMessageConverter converter = new <JsonConverterOfYourChoice>(JsonMapper);

    converter.getSupportedMediaTypes().add(new MediaType("application", "csp-report"));

    然后像您一样将此类转换器注册到 spring 的配置中。

    其他可用的转换器类型包括:
  • StringHttpMessageConverter
  • ObjectToStringHttpMessageConverter(如果你已经配置了 Spring 的 ConversionService 从 String 中读取你想要的类型)
  • ByteArrayHttpMessageConverter
  • FormHttpMessageConverter
  • 生活在 spring.converter.xml 中的各种基于 XML 的转换器包裹
  • AllEncompassingFormHttpMessageConverter(转换器构建在表单转换器之上,也能够处理 XML 和 JSON)
  • Protobuf HttpMessageConverter
  • Atom/RSS馈送消息转换器。

  • 最后,如果以上都不适合您,您可以制作并注册您自己的 HttpMessageConverter 实现。

    关于java - MVC - 当内容类型是自定义的(不是应用程序/json)时接受 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42580662/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com