Spring Boot 中如何解码 WebClient 返回的 Gzip 压缩响应
Spring Boot WebClient Gzip响应解码配置方案
默认情况下WebClient不会自动解码gzip格式的响应,你可以通过以下几种方案实现自动解码,直接得到正常的JSON数据:
方案1:配置底层Reactor Netty HttpClient开启自动解压(推荐)
WebClient默认底层依赖Reactor Netty客户端,直接开启客户端的compress配置即可自动处理gzip/deflate格式的响应解码,同时会自动携带Accept-Encoding请求头,无需手动添加:
import org.springframework.http.client.reactive.ReactorClientHttpConnector; import reactor.netty.http.client.HttpClient; // 1. 配置底层HttpClient开启压缩自动解压 HttpClient httpClient = HttpClient.create() .compress(true); // 2. 基于自定义HttpClient构建WebClient实例 WebClient webClient = WebClient.builder() .clientConnector(new ReactorClientHttpConnector(httpClient)) .build(); // 3. 发起请求的逻辑和你原有逻辑基本一致 webClient.method(HttpMethod.GET) .uri(uriBuilder -> uriBuilder.path(url) .queryParam(attribute1, attribute1) .queryParam(attribute2, attribute2) .build()) .accept(MediaType.APPLICATION_JSON) .acceptCharset(StandardCharsets.UTF_8) .headers(header -> { header.add("Authorization", authHeaders); header.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); // 开启compress后会自动携带Accept-Encoding: gzip,deflate头,这行配置可以省略 // header.add(HttpHeaders.ACCEPT_ENCODING, "gzip"); }).retrieve().bodyToMono(Object.class);
方案2:配置WebClient编解码器开启Gzip解码
如果你不想修改底层客户端配置,也可以直接开启WebClient默认编解码器的gzip解码支持:
WebClient webClient = WebClient.builder() .codecs(configurer -> { // 开启默认编解码器的gzip解码能力 configurer.defaultCodecs().enableGzipDecoder(true); }) .build();
异常场景处理
如果配置后还是拿到乱码,大概率是服务端返回了gzip压缩内容,但响应头没有携带Content-Encoding: gzip标识,导致自动解码逻辑没有触发,你可以自定义过滤器强制解码:
import org.springframework.http.codec.GzipDecoder; import org.springframework.web.reactive.function.client.ExchangeFilterFunction; ExchangeFilterFunction forceGzipDecodeFilter = (request, next) -> next.exchange(request) .flatMap(response -> Mono.just( response.mutate() .body(bodyFlux -> new GzipDecoder().decode(bodyFlux, ResolvableType.forClass(Object.class), MediaType.APPLICATION_JSON, Collections.emptyMap())) .build() )); // 把过滤器添加到WebClient中 WebClient webClient = WebClient.builder() .filter(forceGzipDecodeFilter) .build();
内容的提问来源于stack exchange,提问作者kr.pk
相关产品推荐
相关产品推荐

