我正在编写一个小型 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
如何成功提取请求正文?
最佳答案
post()
返回 WebClient.RequestBodyUriSpec
而不是 ServerResponse
您对 API 的使用不正确。您应该在 search()
方法调用之后使用 .retrieve()
。
在您的情况下,.body()
应用于 POST 请求正文。
您应该继续:
.search().retrieve().bodyToMono(String.class)
关于kotlin - Spring WebFlux,提取请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62598175/