【问题标题】:Getting String body from Spring serverrequest从 Spring serverrequest 获取字符串主体
【发布时间】:2019-06-29 02:16:24
【问题描述】:

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

处理程序:

@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。如何将正文从请求转换为字符串?

【问题讨论】:

  • 请在编码块中包含前两行和最后一个大括号

标签: java spring reactive-programming


【解决方案1】:

您必须阻止才能访问实际的正文字符串:

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

【讨论】:

  • 添加块后出现错误“java.lang.IllegalStateException: block()/blockFirst()/blockLast() 正在阻塞,线程 reactor-http-nio-2 不支持”
  • 工作得很好。非常感谢你。
  • 如果我必须从他们的正文中获取 List 怎么办。那我应该通过哪种类型的课程? @Dan_Maff
【解决方案2】:

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

【讨论】:

  • 添加@RequestBody 后,我在Router 中出现错误“类org.springframework.web.reactive.function.server.RouterFunctions 中的方法路由不能应用于给定类型;”
猜你喜欢
  • 2020-12-01
  • 2019-03-23
  • 1970-01-01
  • 2016-06-01
  • 2014-06-14
  • 2020-07-01
  • 2019-02-06
  • 2012-11-30
  • 1970-01-01
相关资源
最近更新 更多