繁体   English   中英

如何使用 spring 响应式 Web 客户端发送 Body 以使用 Request 方法?

[英]How to send Body in to consume Request method using spring reactive webclient?

我必须使用这个端点: localhost:5100/message/v1?topic=test.state.v2

这个端点需要一个像这样的主体 JSON:

{"topic":"test.state.v2"}

当我使用此 cURL 测试此端点时,会正确返回响应数据。

curl -H "Content-Type: application/json" --request GET --data '{"topic": "test.state.v1"}' http://localhost:5100/test/message/v1

我正在使用这个客户端来消费:

public class MyClient {
//imports.. here

private final String dataStoreHostAndPort = "http://localhost:5100";
private finalJSONObject MY_BODY = new JSONObject().put("topic", "test.state.v1");

    public MyClient(WebClient.Builder builder) {
         HttpClient httpClient = HttpClient.create()
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 200)
                .followRedirect(true)
                .responseTimeout(Duration.ofMillis(200));
    
        webClient = WebClient.builder()
                .baseUrl(dataStoreHostAndPort)
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .build();
    }
    
    
    public Mono<String> getMessage() {
        return this.webClient
                .method(HttpMethod.GET)
                .uri(builder -> builder
                        .path("/message/v1")
                        .queryParam("topic", "log.state.v1").build())
                .body((BodyInserter<?, ? super ClientHttpRequest>) MY_BODY)
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .bodyToMono(String.class);
    }

}

我几乎使用了body(BodyInserter)uri()的所有 forms,但没有任何效果。

如何以与 cURL 相同的方式将MY_BODY发送到 Spring Reactive WebClient请求?

您可以使用.body(BodyInserters.fromValue(YOUR_VALUE_HERE))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM