首页 > 解决方案 > 从 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。如何将正文从请求转换为字符串?

标签: javaspringreactive-programming

解决方案


您将不得不阻止以获取实际的正文字符串:

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);
        }

推荐阅读