如何在没有 Spring Boot 的情况下使用 Spring WebClient

Fin*_*ber 4 spring spring-boot spring-webclient

我对能够发出 HTTP 请求的需求非常有限。我看到 WebClient 是 RestTemplate 的新替代品。但是好像不能用WebClient,不拖整个spring boot;这不是我想做的。有没有办法在没有 Spring Boot 的情况下使用 WebClient?

小智 5

您可以使用 Reactor Netty HttpClient ( docs )发出异步 HTTP 请求。Spring WebClient 在幕后使用它。只需添加依赖

<dependency>
    <groupId>io.projectreactor.netty</groupId>
    <artifactId>reactor-netty</artifactId>
    <version>0.9.11.RELEASE</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

并提出要求

HttpClient.create()
            .request(HttpMethod.GET)
            .uri("http://example.com/")
            .responseContent()
            .asString()
            .subscribe(System.out::println);
Run Code Online (Sandbox Code Playgroud)

  • 我将 WebClient 的使用替换为建议的 HttpClient,一切正常。我接受这个答案,尽管从技术上讲,它并不是如何在没有 Spring Boot 的情况下使用 Spring WebClient 的答案 - 我认为这是不可能的。 (2认同)