gpt4 book ai didi

spring - 从 Spring 的 rest Controller 同时支持 application/json 和 application/x-www-form-urlencoded

转载 作者:行者123 更新时间:2023-12-01 03:17:37 39 4
gpt4 key购买 nike

我正在编写一个 REST 端点,它需要同时支持 application/x-www-form-urlencoded 和 application/json 作为请求主体。我做了以下配置,

@RequestMapping(method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE }, consumes = {          
MediaType.APPLICATION_FORM_URLENCODED_VALUE, MediaType.APPLICATION_JSON_VALUE }, path = Constants.ACCESS_TOKEN_V1_ENDPOINT)
public OAuth2Authorization createAccessTokenPost(
@RequestBody(required = false) MultiValueMap<String, String> paramMap) { ..

虽然它单独支持 application/x-www-form-urlencoded 或 application/json (当我从 consumes = {} 注释掉一种内容类型时),但它不能同时支持两者。有任何想法吗 ?

最佳答案

所以 RestControllers 默认可以处理 application/json相当容易,并且可以从 @RequestBody 创建请求 pojo带注释的参数,而 application/x-www-form-urlencoded需要更多的工作。一个解决方案可能是创建一个额外的 RestController 方法,该方法具有相同的映射端点来处理传入的不同类型的请求( application/json, application/x-www-form-urlencoded 等)。这是因为 application/x-www-form-urlencoded端点需要使用 @RequestParam而不是 @RequestBody注释(用于 application/json )。
例如,如果我想为 /emp 托管一个 POST 端点。这需要application/jsonapplication/x-www-form-urlencoded作为 Content-Types 并使用服务来做某事,我可以像这样创建重载方法

@Autowired
private EmpService empService;

@PostMapping(path = "/emp", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
public ResponseEntity createEmp(final @RequestHeader(value = "Authorization", required = false) String authorizationHeader,
final @RequestParam Map<String, String> map) {
//After receiving a FORM URLENCODED request, change it to your desired request pojo with ObjectMapper
final ObjectMapper mapper = new ObjectMapper();
final TokenRequest tokenRequest = mapper.convertValue(map, CreateEmpRequest.class);
return empService.create(authorizationHeader, createEmpRequest);
}

@PostMapping(path = "/emp", consumes = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity createEmp(final @RequestHeader(value = "Authorization", required = false) String authorizationHeader,
final @RequestBody CreateEmpRequest createEmpRequest) {
//Receieved a JSON request, the @RequestBody Annotation can handle turning the body of the request into a request pojo without extra lines of code
return empService.create(authorizationHeader, createEmpRequest);
}

关于spring - 从 Spring 的 rest Controller 同时支持 application/json 和 application/x-www-form-urlencoded,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47924463/

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