我试图从请求正文中获取简单的字符串,但不断收到错误
Handler:
@RestController
public class GreetingHandler {
public Mono<ServerResponse> hello(ServerRequest request) {
String contentType = request.headers().contentType().get().toString();
String body = request.bodyToMono(String.class).toString();
return ServerResponse.ok().body(Mono.just("test"), String.class);
}
}
Router:
@Configuration
public class GreetingRouter {
@Bean
public RouterFunction<ServerResponse> route(GreetingHandler greetingHandler) {
return RouterFunctions
.route(RequestPredicates.POST("/hello"),greetingHandler::hello);
}
}
请求有效,我可以看到内容类型(plainTexT),并且我在邮递员中得到响应,但我无法获取请求正文。我遇到的最常见错误是 MonoOnErrorResume。如何将请求正文转换为字符串?
您必须阻止才能到达实际的正文字符串:
String body = request.bodyToMono(String.class).block();
toString()
只会给你你的字符串表示Mono
object.
这是块的作用:https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#block-- https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#block--
Update:
我不知道在 http 线程上阻塞是不可能的(不再?)。
这是您的改编版本hello
控制器方法,在控制台上打印“Hello yourInput”,并在响应中返回该字符串。
public Mono<ServerResponse> hello(ServerRequest request) {
Mono<String> requestMono = request.bodyToMono(String.class);
Mono<String> mapped = requestMono.map(name -> "Hello " + name)
.doOnSuccess(s -> System.out.println(s));
return ServerResponse.ok().body(mapped, String.class);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)