java - 从 Spring serverrequest 获取字符串主体
问题描述
我正在尝试从请求正文中获取简单的字符串,但不断收到错误
处理程序:
@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);
}
}
路由器:
@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
对象的字符串表示形式。
这是块的作用: https ://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#block--
更新:
我不知道在 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);
}
推荐阅读
- sql - 使用 Oracle 中的条件更新表
- rust - 如果 Rust 项目已更新,则重新运行规则
- python-3.x - html和python与flask的集成
- sql - 创建一个变量来存储在公司工作超过 3 年的员工人数
- ngrx - ngrx/data 无法让 selectId 使用 Id 而不是 id
- javascript - 保护访问令牌免受 XSS 攻击
- node.js - request.body.name 在 expressjs 应用程序中不起作用
- forms - 我需要在 a 中展示产品。落下
- node.js - 我必须将此行变量发送到前端。我无法在 app.post 方法中编写 app.get() 方法。请问如何解决这个问题
- visual-studio-code - 复制“代码”的 Visual Studio 代码窗口。命令