可以同时拥有 Spring @RequestBody 和 HttpEntity 吗?
Possible to have Spring @RequestBody and HttpEntity at the same time?
我的 Spring 引导应用程序中有以下代码:
@RestController
@RequestMapping("/execute")
public class RestCommandExecutor {
@PostMapping
public Response executeCommand(@RequestBody Command command,
HttpEntity<String> httpEntity) {
System.out.println(command);
System.out.println("********* payload is: " + httpEntity.getBody());
return new Response("Hello text", new Long(123));
}
}
当 POST 请求带有正确的 Command
时,我得到一个 I/O 错误:
.w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: I/O error while reading input message; nested exception is java.io.IOException: Stream closed
我想 Spring 将请求正文翻译成 Command
,但由于 JSON 比 Command
[=31] 包含更多内容=],我也想获得完整的 JSON 原始格式。
有没有办法通过方法中的映射来实现?我知道我总是可以这样做 public Response executeCommand(HttpEntity<String> httpEntity)
然后使用 Jackson 手动将其翻译成 Command
,但我宁愿不必手动这样做。
这可能吗?
您不能同时读取 HttpEntity
的正文和使用 @RequestBody
的原因是既读取 HttpRequest
的 InputStream
又关闭它然后。由于关闭后无法从 InputStream
再次读取,因此如您所见,最后一次操作失败。
看来您真正想要的是访问一些未在 Command
class 中映射的属性,尤其是使用 type
指定的 class 属性。
您可以使用 Jackson 的 @JsonTypeInfo
和 @JsonSubtype
注释来执行此操作,这允许您自定义 class 层次结构的反序列化。
我的 Spring 引导应用程序中有以下代码:
@RestController
@RequestMapping("/execute")
public class RestCommandExecutor {
@PostMapping
public Response executeCommand(@RequestBody Command command,
HttpEntity<String> httpEntity) {
System.out.println(command);
System.out.println("********* payload is: " + httpEntity.getBody());
return new Response("Hello text", new Long(123));
}
}
当 POST 请求带有正确的 Command
时,我得到一个 I/O 错误:
.w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: I/O error while reading input message; nested exception is java.io.IOException: Stream closed
我想 Spring 将请求正文翻译成 Command
,但由于 JSON 比 Command
[=31] 包含更多内容=],我也想获得完整的 JSON 原始格式。
有没有办法通过方法中的映射来实现?我知道我总是可以这样做 public Response executeCommand(HttpEntity<String> httpEntity)
然后使用 Jackson 手动将其翻译成 Command
,但我宁愿不必手动这样做。
这可能吗?
您不能同时读取 HttpEntity
的正文和使用 @RequestBody
的原因是既读取 HttpRequest
的 InputStream
又关闭它然后。由于关闭后无法从 InputStream
再次读取,因此如您所见,最后一次操作失败。
看来您真正想要的是访问一些未在 Command
class 中映射的属性,尤其是使用 type
指定的 class 属性。
您可以使用 Jackson 的 @JsonTypeInfo
和 @JsonSubtype
注释来执行此操作,这允许您自定义 class 层次结构的反序列化。