我發送了如下請求。
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嗎?
uj5u.com熱心網友回復:
您不應該顯式訂閱 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"))
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/489573.html
標籤:爪哇 休息 卷曲 spring-webflux
