【问题标题】:Find the Content-type of the incoming request in Spring boot在 Spring boot 中查找传入请求的 Content-type
【发布时间】:2021-10-18 09:27:18
【问题描述】:

我有一个将由前端调用的 Spring-Boot 控制器应用程序。 Spring-boot @PostMapping 将接受 XMLJSON。我想根据Content-Type调用不同的方法。

有没有办法检查传入的内容类型是什么?

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/api")
public class MyController {
    
    @PostMapping(value = "/generator", consumes = {"application/json", "application/xml"}, produces = "application/json")
    public String generate(@RequestBody String input) {
        try {
            System.out.println("INPUT CONTENT TYPE : ");
            if(contentType == "application/xml")
            {
                //Call Method-1
            }else if(contentType == "application/json"){
                //Call Method-2
            }
        } catch (Exception exception) {
            System.out.println(exception.getMessage());
        }
    }

}

我们可以看到RestController 方法接受XML and JSON。我想检查传入的Content-type 是基于它做出不同决定的需要。谁能给我解释一下怎么做?

请注意: 我知道我可以创建不同的方法来处理 XML 和 JSON,但我想用一个方法来完成,这样既简单又高效。

【问题讨论】:

    标签: java json spring spring-boot content-type


    【解决方案1】:

    添加RequestHeader 及其名称Content-type

    public String generate(@RequestBody String input, @RequestHeader("Content-type") String contentType)
    

    指示方法参数应绑定到 Web 请求标头的注释。

    【讨论】:

      【解决方案2】:

      你可以使用

      @RequestHeader Map<String, String> headers
      

      您的 generate() 方法的内部参数用于获取所有 Header 来自客户端。

      之后,只需检查

      内容类型

      价值

      【讨论】:

        猜你喜欢
        • 2018-06-21
        • 2019-10-19
        • 2022-10-07
        • 2022-07-15
        • 2020-10-27
        • 2021-10-31
        • 2021-08-02
        • 2012-08-14
        • 1970-01-01
        相关资源
        最近更新 更多