【问题标题】:Replace HTTPClient with WebClient in Java在 Java 中将 HTTPClient 替换为 WebClient
【发布时间】:2020-12-10 11:04:05
【问题描述】:
        String url = "https://localhost:8080/api/V1/hr/Auth";

        HttpClient client = httpClientFactory.getHttpClient();
        HttpPost request = new HttpPost(url);
        request.addHeader("content-type", "application/json");
        request.addHeader("clientUniqueId", "");
        request.addHeader("language", "English");

        jsonObject.put("UserName", "");
        jsonObject.put("Password", "");

        StringEntity params = new StringEntity(jsonObject.toString());

        request.setEntity(params);
        HttpResponse response;
        response = client.execute(request);
        String responseAsString = EntityUtils.toString(response.getEntity());

我需要用 WebClient 替换 httpClient 我使用了 webflux 依赖项。 并尝试过

HttpRequest request1 = (HttpRequest) webClientBuilder
                                         .build()
                                         .post()
                                         .uri(url)
                                         .header("content-type", "application/json")
                                         .header("clientUniqueId", "")
                                         .header("language", "English");

提前致谢。

【问题讨论】:

    标签: java spring spring-boot spring-webclient


    【解决方案1】:

    也许这个链接可以帮助你springframework.guru

    【讨论】:

    • 感谢链接,但是当我们在 httpclient 中发送 StringEntity 参数时,我们如何在 webclient 中发送它
    【解决方案2】:

    首先要注意的是,您应该构建一次网络客户端,并在可能的情况下重复使用它。使用最常见的配置构建它,以便使用它发出的每个请求都需要最少的配置。

    最简单的 WebClient 会这样构建:

    WebClient webClient = WebClient.builder()
                                   .build();
    

    现在您可以使用 webClient 发出请求。

    Mono<String> responseAsString =
            webClient
            .post()
            .uri(uri)
            .contentType(MediaType.APPLICATION_JSON)
            .header("clientUniqueId", "")
            .header("language", "English")
            .bodyValue(jsonObject)
            .exchangeToMono(response -> response.bodyToMono(String.class));
    

    有一个方便的方法contentType 可以为您添加标题名称。 您可以使用 bodyValue 传递正文值,这将自动将其序列化为 JSON(由于指定的内容类型)。

    exchangeToMono 是实际发出请求配置结束信号的方法,并配置将如何处理响应。在这种情况下,我们将响应转换为String。更具体地说,MonoStringWebClient 是“反应式”。这意味着它适用于您正在构建对数据进行操作的流的想法。在上面的流中,数据被发送到将其转换为响应的 API。我们已经发出信号,必须将响应转换为String

    我们仍然只有Mono&lt;String&gt;。如果你运行代码,什么都不会发生。您必须订阅流才能发生某些事情。

    responseAsString.subscribe(System.out::println);
    

    会将输出打印到标准输出。

    如果你在某个 main 方法中运行它只是为了测试,你需要等待订阅,或者只是阻塞:

    System.out.println(responseAsString.block());
    

    【讨论】:

    • 我观察到使用单个 webclient bean 是内存峰值和 cpu 峰值
    • 在我们的多租户案例中,我们使用 webclient 配置为每个客户端扩展 - 并根据租户传递不同的 url ---
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-15
    相关资源
    最近更新 更多