在 Spring 引导中查找传入请求的内容类型
Find the Content-type of the incoming request in Spring boot
我有一个 Spring- 将由前端调用的引导控制器应用程序。 Spring-boot @PostMapping
会接受 XML
和 JSON
。我想根据 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
。我想检查whats传入的Content-type
是根据其需要做出不同的决定。有人可以向我解释如何操作吗?
请注意:
我知道我可以创建不同的方法来处理 XML 和 JSON,但我想用一个方法来做,这样既简单又高效。
您可以使用
@RequestHeader Map<String, String> headers
用于获取所有 Header 的 generate() 方法的内部参数来自客户端。
之后,只需检查
Content-Type
价值
添加 RequestHeader 及其名称 Content-type
:
public String generate(@RequestBody String input, @RequestHeader("Content-type") String contentType)
Annotation which indicates that a method parameter should be bound to a web request header.
我有一个 Spring- 将由前端调用的引导控制器应用程序。 Spring-boot @PostMapping
会接受 XML
和 JSON
。我想根据 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
。我想检查whats传入的Content-type
是根据其需要做出不同的决定。有人可以向我解释如何操作吗?
请注意: 我知道我可以创建不同的方法来处理 XML 和 JSON,但我想用一个方法来做,这样既简单又高效。
您可以使用
@RequestHeader Map<String, String> headers
用于获取所有 Header 的 generate() 方法的内部参数来自客户端。
之后,只需检查
Content-Type
价值
添加 RequestHeader 及其名称 Content-type
:
public String generate(@RequestBody String input, @RequestHeader("Content-type") String contentType)
Annotation which indicates that a method parameter should be bound to a web request header.