[英]How to get request body from ServerRequest object in Spring WebFlux reactive?
[英]Body in serverRequest is null with ServerRequest(Spring Webflux)
我发送了如下请求。
curl -d "{""key1"":""value1"", ""key2"":""value2""}" \
-H "Content-Type: application/json" \
-X POST http://localhost:8080/myApi/test
并编写路由配置如下
RouterFunctions.route()
.path("/myApi", builder -> builder
.POST("/test", handler::test))
.build();
在处理程序::测试中,
public Mono<ServerResponse> test(ServerRequest serverRequest) {
System.out.println(serverRequest.headers());
serverRequest.bodyToMono(String.class).subscribe(System.out::println);
return ServerResponse.ok().body(Mono.just("ok"), String.class);
}
但结果如下。
[Host:"localhost:8080", User-Agent:"curl/7.77.0", Accept:"*/*", Content-Type:"application/json", content-length:"26"]
我添加一行来检查正文是否为空,结果如下。
System.out.println(serverRequest.bodyToMono(String.class).toProcessor().peek());
null
有什么方法可以从ServerRequest
中提取正文?
您不应该显式订阅 WebFlux 中的发布者。 如果您在调试模式下运行并在return
语句上放置断点,您会看到
Caused by: java.lang.IllegalStateException: Only one connection receive subscriber allowed.
在运行时,此错误不可见,因为subscribe
是异步的,并且您的代码甚至在它之前就退出了。
无论如何,正确的实现看起来像
public Mono<ServerResponse> test(ServerRequest serverRequest) {
return serverRequest.bodyToMono(String.class)
.doOnNext(System.out::println)
.flatMap(body -> ServerResponse.ok()
.body(BodyInserters.fromValue("ok"))
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.