繁体   English   中英

从Spring服务器获取字符串体

[英]Getting String body from 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);


    }
}

请求工作,我可以看到contenType(plainTexT),我在邮递员中得到响应,但是我无法请求请求正文。 我收到的最常见错误是MonoOnErrorResume。 如何将正文从请求转换为字符串?

可以使用@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);
    }

您将需要阻塞才能到达实际的主体字符串:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM