kotlin - Spring WebFlux,提取请求正文

标签 kotlin spring-webflux reactive

我正在编写一个小型 WebFlux 客户端代理,它将接受 POST 请求、提取 JSON 内容,并通过另一个 POST 将其传递给对第三方 Web 服务器的进一步调用。我想获取原始 POST 请求中的 json 正文。

curl --header "Content-Type: application/json" \
  --request POST \
  --data '{"username":"xyz", "preference":"123"}' \
  http://localhost:3000/mih/search

这是我处理上述 POST 的路线:

@Bean
open fun route(searchService: SearchService): RouterFunction<ServerResponse> {
    return RouterFunctions.route(
            RequestPredicates.POST("/search").and(RequestPredicates.accept(MediaType.APPLICATION_JSON)),
            HandlerFunction {
                    request: ServerRequest -> searchService.search(request.body(BodyExtractors.toMono(String::class.java)))
            } )
    }
open class SearchService(private val myWebClient: MyWebClient): ISearchService {

    override fun search(json: String): Mono<ServerResponse> {
        return myWebClient.myPost(json)
    }
}
import org.springframework.web.reactive.function.client.WebClient

open class MyWebClient(
    private val springWebClient: WebClient,
    private val properties: properties ) : IMyWebClient {

    override fun myPost(json: String): Mono<ServerResponse> {
        return springWebClient.post()
            .uri("/{base}/queries", properties.getBase)
            .body(
                BodyInserters.fromPublisher(Mono.just(json), String::class.java)
            ).retrieve().bodyToMono(
                ServerResponse::class.java
            )
    }
}

当我访问.subscribe()时到Mono<String>我明白

Type mismatch.
  Required: String
  Found: Disposable

如何成功提取请求正文?

最佳答案

根据文档: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/reactive/function/client/WebClient.html#post--

post() 返回 WebClient.RequestBodyUriSpec 而不是 ServerResponse

您对 API 的使用不正确。您应该在 search() 方法调用之后使用 .retrieve()

在您的情况下,.body() 应用于 POST 请求正文。

您应该继续:

.search().retrieve().bodyToMono(String.class)

关于kotlin - Spring WebFlux,提取请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62598175/

相关文章:

Android Kotlin - 如何读取 Activity 内的 NFC 标签

arrays - 为Kotlin中的每个元素增值

reactive-programming - map 和 doOnNext 有什么区别? (即项目 react 堆)

java - 如何立即从 Mono.zip 返回服务器发送的事件?

dictionary - 未调用 http 响应上的 RxJs/Angular2 映射函数

spring-boot - 响应式(Reactive)编程 : Spring WebFlux: How to build a chain of micro-service calls?

java - Kotlin 的 JvmDefault - 仍然需要声明该方法吗?

java - 检查当前是否显示锁屏

java - 我应该在 Spring 5 项目中使用具有实体关系的 MongoDB 来实现端到端非阻塞吗?

scope - 带有 onMount 变量的 Svelte 响应式(Reactive)语句