gpt4 book ai didi

java - 带有 PathVariable 的 API 的 XML 响应

转载 作者:行者123 更新时间:2023-11-29 08:21:20 24 4
gpt4 key购买 nike

我有 API:

@GetMapping(path = "/users/{userId}")
public ResponseEntity<UserDTO> getUserById(@PathVariable(value = "userId") Long userId) {
//logic here
}

它应该返回 JSON 响应。

还有另一个我无权访问的应用程序,它调用我的 API,例如 GET/users/123.xml 以接收 XML 响应。

但在这种情况下,我的 API 失败并出现 400 错误,因为它无法将 123.xml 解析为 Long

选项 @GetMapping(value = {"/users/{userId}", "/users/{userId}.xml"}) 失败并出现同样的错误。

在调用 /{userId}.xml 时如何使用 XML 语法进行响应,同时在调用 /{userId} 时使用 JSON 语法进行响应?

编辑:

我希望它无需专门添加“接受” header ,也无需编写任何额外的逻辑,它将解析 {userId}.xml,然后设置适当的响应类型。

最佳答案

这可以通过使用 ContentNegotiationConfigurer 来完成,您可以按如下方式配置它:

@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.defaultContentType(MediaType.APPLICATION_JSON)
.mediaType("xml", MediaType.APPLICATION_XML)
.mediaType("json", MediaType.APPLICATION_JSON);
}
}

它应该适用于您的端点:

@GetMapping(path = "/users/{userId}", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
public ResponseEntity<UserDTO> getUserById(@PathVariable(value = "userId") Long userId) {
return new ResponseEntity<>(userService.get(userId), HttpStatus.OK);
}

关于java - 带有 PathVariable 的 API 的 XML 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57866140/

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