Java 从Spring服务器请求获取字符串正文
我试图从请求体中获取简单字符串,但不断出现错误 处理程序:Java 从Spring服务器请求获取字符串正文,java,spring,reactive-programming,Java,Spring,Reactive Programming,我试图从请求体中获取简单字符串,但不断出现错误 处理程序: @RestController public class GreetingHandler { public Mono<ServerResponse> hello(ServerRequest request) { String contentType = request.headers().contentType().get().toString(); String body
@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);
}
}
@RestController
公共类迎宾处理程序{
公共Mono hello(服务器请求){
字符串contentType=request.headers().contentType().get().toString();
String body=request.bodytomino(String.class.toString();
返回ServerResponse.ok().body(Mono.just(“test”),String.class);
}
}
路由器:
@Configuration
public class GreetingRouter {
@Bean
public RouterFunction<ServerResponse> route(GreetingHandler greetingHandler) {
return RouterFunctions
.route(RequestPredicates.POST("/hello"),greetingHandler::hello);
}
}
@配置
公共类迎宾路由器{
@豆子
公共路由器功能路由(GreetingHandler GreetingHandler){
返回路由函数
.route(RequestPredicates.POST(“/hello”)、greetingHandler::hello);
}
}
请求工作我可以看到contenType(纯文本),我在postman中得到了响应,但我无法访问请求正文。我遇到的最常见的错误是MononerrorResume。如何将请求的正文转换为字符串 您可以使用
@RequestBody
注释吗
public Mono<ServerResponse> hello(@RequestBody String body, ServerRequest request) {
String contentType = request.headers().contentType().get().toString();
return ServerResponse.ok().body(Mono.just("test"), String.class);
}
公共Mono hello(@RequestBody字符串body,ServerRequest){
字符串contentType=request.headers().contentType().get().toString();
返回ServerResponse.ok().body(Mono.just(“test”),String.class);
}
您必须阻塞才能获得实际的正文字符串:
String body=request.bodytomino(String.class.block()代码>
toString()
将只提供Mono
对象的字符串表示形式
以下是block的功能:
更新:
我没有意识到在http线程上阻塞是不可能的(再也不可能了?)。
这里是您的hello
控制器方法的一个改编版本,它在控制台上打印“helloyourinput”,并在响应中返回该字符串
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);
}
公共Mono hello(服务器请求){
Mono-requestMono=request.bodytomino(String.class);
Mono-mapped=requestMono.map(name->“Hello”+name)
.doOnSuccess->System.out.println;
返回ServerResponse.ok().body(已映射,String.class);
}
请在编码块和最后一个括号中包含前2行,在添加@RequestBody i get a error in Router“类org.springframework.web.reactive.function.server.RouterFunctions中的方法路由无法应用于给定的类型”之后,请在编码块和最后一个括号中添加@RequestBody i get a error“java.lang.IllegalStateException:block()/blockFirst()/blockLast()线程reactor-http-nio-2“运行良好”中不支持的阻塞。非常感谢你。