From e2de3c1a169d440c9b952ab2fb79706a72285a9e Mon Sep 17 00:00:00 2001 From: asahi Date: Sun, 27 Apr 2025 12:55:24 +0800 Subject: [PATCH] =?UTF-8?q?doc:=20=E9=98=85=E8=AF=BBwebclient=E6=96=87?= =?UTF-8?q?=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- spring/webflux/webclient.md | 66 +++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/spring/webflux/webclient.md b/spring/webflux/webclient.md index e1c8e23..cfb57bf 100644 --- a/spring/webflux/webclient.md +++ b/spring/webflux/webclient.md @@ -163,3 +163,69 @@ WebClient.create().get() #### connectTimeout 以ms为单位指定一个超时时长,当与服务端建立连接时,如果超过该时长后连接仍未建立,那么将会抛出`java.net.SocketTimeoutException`异常。 +### JDK HttpClient +如果要自定义jdk httpclient配置,欸可以使用如下方式: +```java +HttpClient httpClient = HttpClient.newBuilder() + .followRedirects(Redirect.NORMAL) + .connectTimeout(Duration.ofSeconds(20)) + .build(); + +ClientHttpConnector connector = + new JdkClientHttpConnector(httpClient, new DefaultDataBufferFactory()); + +WebClient webClient = WebClient.builder().clientConnector(connector).build(); +``` + +### Jetty +自定义jetty httpclient配置的示例如下所示: +```java +HttpClient httpClient = new HttpClient(); +httpClient.setCookieStore(...); + +WebClient webClient = WebClient.builder() + .clientConnector(new JettyClientHttpConnector(httpClient)) + .build(); +``` + +### HttpComponents +如下示例展示了如何定义Apache HttpComponents: +```java +HttpAsyncClientBuilder clientBuilder = HttpAsyncClients.custom(); +clientBuilder.setDefaultRequestConfig(...); +CloseableHttpAsyncClient client = clientBuilder.build(); + +ClientHttpConnector connector = new HttpComponentsClientHttpConnector(client); + +WebClient webClient = WebClient.builder().clientConnector(connector).build(); +``` + +## retrieve() +`retrieve()`方法用于定义`如何对相应进行提取`,示例如下: +```java +WebClient client = WebClient.create("https://example.org"); + +Mono> result = client.get() + .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON) + .retrieve() + .toEntity(Person.class); +``` +上述示例获取的是`ResponseEntity`,如果想要直接获取`Persion`类型的response body,可以通过如下方式进行获取: +```java +WebClient client = WebClient.create("https://example.org"); + +Mono result = client.get() + .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON) + .retrieve() + .bodyToMono(Person.class); +``` +默认情况下,`4xx`或`5xx`的http响应将会导致`WebClientResponseException`,如果需要自定义error handling逻辑,需要使用`onStatus`,示例如下: +```java +Mono result = client.get() + .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON) + .retrieve() + .onStatus(HttpStatusCode::is4xxClientError, response -> ...) + .onStatus(HttpStatusCode::is5xxServerError, response -> ...) + .bodyToMono(Person.class); +``` +