使用 webclient 调用 spring boot rest 接口,核心是构建客户端实例并链式调用 http 方法。直接通过 webclient.builder().build() 创建实例后,利用 .get()、.post() 等方法指定 url,配合 .retrieve() 处理响应体或错误状态码,即可实现同步通信。若需处理请求头、参数或自定义超时,可在链中插入对应配置节点。

WebClient 如何发送带参数的 GET 请求并解析 JSON 响应
发送带参数的 GET 请求并解析 JSON,需使用 .uri() 传入路径和查询参数,并通过 .bodyToMono() 将响应体反序列化为 Java 对象。默认情况下,WebClient 依赖 Jackson 进行 JSON 转换,因此确保类路径下有 Jackson 依赖且实体类字段与 JSON 键名匹配是关键。若响应状态码非 2xx,.retrieve() 会抛出 WebClientResponseException,需在代码中捕获或配置全局错误处理器。

import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
public class Demo {
public static void main(String[] args) {
WebClient client = WebClient.create("http://localhost:8080");
Mono<user> userMono = client.get()
.uri("/users/{id}", "1")
.retrieve()
.bodyToMono(User.class);
User user = userMono.block();
System.out.println(user.getName());
}
static class User { private String name; public String getName() { return name; } public void setName(String n) { name = n; } }
}</user>
WebClient 如何处理 POST 请求中的请求头与 Body 序列化
处理 POST 请求时,需通过 .header() 设置 Content-Type 等请求头,并使用 .bodyValue() 或 .body() 传入请求体。Spring Boot 默认使用 Jackson 将 Java 对象序列化为 JSON,因此只需传入实体对象即可,无需手动构造 JSON 字符串。若服务端要求特定的字符编码或认证信息,应在请求构建阶段显式添加相关 Header,否则可能导致 401 或 415 错误。

import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
public class PostDemo {
public static void main(String[] args) {
WebClient client = WebClient.create("http://localhost:8080");
Mono<string> response = client.post()
.uri("/users")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(new User("Alice"))
.retrieve()
.bodyToMono(String.class);
System.out.println(response.block());
}
static class User { private String name; public User(String n) { name = n; } }
}</string>
当 REST 接口返回 404 时 WebClient 的行为表现是什么
当 REST 接口返回 404 时,WebClient 不会自动抛出异常,而是将响应体作为普通数据流传递。若未配置错误过滤器,.retrieve() 会继续执行后续操作,导致 bodyToMono() 尝试解析空或非预期格式的响应体,可能引发反序列化异常。开发者需通过 .onStatus() 注册状态码检查逻辑,或在 .exchangeToMono() 中手动判断状态码,以区分业务错误和网络错误。











