我使用的是Java2.5.2版本的WebFlux。我需要提取纯文本,这是作为POST请求来的,然后我将不得不处理文本。如何从ServerRequest对象中提取身体?
我正在粘贴路由器和处理程序代码。将图像附加到“监视”窗口,该窗口显示代码的错误,我试图提取有效载荷。

路由器类如下:
package com.test;
import com.test.AppHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import static org.springframework.web.reactive.function.server.RequestPredicates.*;
@Configuration
public class AppRouter {
@Bean
public RouterFunction<ServerResponse> route(AppHandler appHandler){
return RouterFunctions
.route(GET("/").and(accept(MediaType.TEXT_PLAIN)), appHandler::ping)
.andRoute(POST("/process").and(accept(MediaType.ALL)).and(contentType(MediaType.TEXT_PLAIN)), appHandler::process);
}
}Handler类如下:
package com.test;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
@Component
public class AppHandler {
public Mono<ServerResponse> process(ServerRequest request){
//Extract the request body
Mono<String> responseBody = request.bodyToMono(String.class);
responseBody.map(s -> s + " -- added on the server side.");
return ServerResponse.ok()
.body(responseBody.log(), String.class);
}
public Mono<ServerResponse> ping(ServerRequest request){
return ServerResponse.ok()
.contentType(MediaType.TEXT_PLAIN)
.body(Mono.just("PONG").log(), String.class);
}
}pom依赖关系的提取
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
...
<dependencies>发布于 2021-07-01 22:54:30
您发布的错误不是来自您发布的代码。不允许在反应性应用程序中阻塞,并且使用关键字block,这意味着您正在获得一个IllegalStateException,因为阻塞是非法的。
然后,在您已经发布的代码中,问题是您正在打破链。
responseBody.map(s -> s + " -- added on the server side.");这行只是一个声明,但是是nothing happens until you subscribe,没有任何东西订阅这一行,因此您需要跟踪它并处理来自map函数的返回。
return responseBody.flatMap(s -> {
return ServerResponse.ok()
.body(Mono.just(s + " -- added on the server side."), String.class);
});当客户端调用您的应用程序时,它们是订阅的,因此您必须确保服务器端的链是完整的,以便我们可以将项目提供给客户端。但是您没有处理上面行中的返回,所以没有发生任何事情。
https://stackoverflow.com/questions/68214510
复制相似问题