Java/Spring MVC:列出媒体类型/读取内容协商设置

我想创建一个端点,告诉用户为 contentNegotiation 注册了哪些媒体类型。

这些是我的设置

     configurer
            .favorPathExtension(false)
            .favorParameter(true)
            .parameterName("mediaType")
            .ignoreAcceptHeader(true)
            .useJaf(false)
            .defaultContentType(MediaType.APPLICATION_JSON_UTF8)
            .mediaType("json", MediaType.APPLICATION_JSON_UTF8)
            .mediaType("pdf", MediaType.APPLICATION_PDF)
            .mediaType("html", MediaType.TEXT_HTML)
            .mediaType("csv", new MediaType("text", "csv"));

如何在控制器中读取它们?我希望有一些函数 whatService.getMediaTypes 返回 ["json", "pdf", "html", "csv"]。

编辑:
或者一种获取所有 AbstractHttpMessageConverter 及其 MediaType 的方法。


扬帆大鱼
浏览 201回答 2
2回答

慕后森

尝试这样的事情:@RestControllerpublic class YourRest {&nbsp; &nbsp; ...&nbsp; &nbsp; @Autowired&nbsp; &nbsp; private ContentNegotiationManager contentNegotiationManager;&nbsp; &nbsp; @RequestMapping(value = "types", method = RequestMethod.GET)&nbsp; &nbsp; public Set<String> getConfiguredMediaTypes() {&nbsp; &nbsp; &nbsp; &nbsp; return Optional.of(contentNegotiationManager)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(m -> m.getStrategy(ParameterContentNegotiationStrategy.class))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(s -> s.getMediaTypes().keySet())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .orElse(Collections.emptySet());&nbsp; &nbsp; }&nbsp; &nbsp; ...}

慕桂英3389331

Content-Type 是一个请求头,您可以使用以下代码获取它:@RequestMapping("/your-endpoint")public void endpoint(@RequestHeader("Content-Type") String contentType)&nbsp; {}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java