从 Spring serverrequest 获取 String body [英] Getting String body from Spring serverrequest

查看:41
本文介绍了从 Spring serverrequest 获取 String body的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从请求正文中获取简单的字符串,但不断收到错误

I am trying to get simple string from request body but keep getting errors

处理程序:

@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.如何将主体从请求转换为字符串?

Request works i can see the contenType (plainTexT) and i get the response in postman but no way i cant get to request body. The most common error i get is MonoOnErrorResume. How do i convert the body from request into String?

推荐答案

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

You will have to block to get to the actual body string:

String body = request.bodyToMono(String.class).block();

toString() 只会给你你的 Mono 对象的字符串表示.

toString() will just give you the string representation of your Mono object.

这是块的作用:https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#block--

更新:

我不知道在 http 线程上阻塞是不可能的(不再?).这是您的 hello 控制器方法的改编版本,它在控制台上打印Hello yourInput"并在响应中返回该字符串.

I wasn't aware that blocking on the http thread is not possible (anymore?). Here is an adapted version of your hello controller method that prints "Hello yourInput" on the console and also returns that string in the response.

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

这篇关于从 Spring serverrequest 获取 String body的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆