代码之家  ›  专栏  ›  技术社区  ›  Nestor Javier Moreno Rodriguez

如何使用spring反应式webclient将正文发送到消费请求方法?

  •  1
  • Nestor Javier Moreno Rodriguez  · 技术社区  · 4 年前

    我必须使用此端点: 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() 但什么都没用。

    如何发送 MY_BODY 至弹簧被动 WebClient 以与cURL相同的方式请求?

    0 回复  |  直到 4 年前
        1
  •  0
  •   red    4 年前

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