Spring Boot WebClient如何从ClientResponse获取响应状态原因短语
WebClient获取服务端自定义响应原因短语方案
WebClient上层API默认没有暴露原始响应原因短语,可通过自定义底层HTTP客户端的方式捕获该值,具体实现如下:
1. 自定义底层Reactor Netty HttpClient
默认WebClient底层基于Reactor Netty实现,我们可以在HttpClient层面拦截原始响应,拿到状态行中的自定义原因短语,存入响应头传递到上层:
import reactor.netty.http.client.HttpClient; HttpClient customHttpClient = HttpClient.create() .doOnResponse((connection, response) -> { // 直接获取Netty原生响应的原始原因短语 String rawReasonPhrase = response.status().reasonPhrase(); // 写入自定义响应头,方便上层ClientResponse读取 connection.responseHeaders().add("X-Custom-Status-Reason", rawReasonPhrase); });
2. 用自定义HttpClient构造WebClient实例
import org.springframework.http.client.reactive.ReactorClientHttpConnector; import org.springframework.web.reactive.function.client.WebClient; WebClient customWebClient = WebClient.builder() .clientConnector(new ReactorClientHttpConnector(customHttpClient)) .build();
3. 业务调用时读取原因短语提取LogId
import java.util.regex.Matcher; import java.util.regex.Pattern; import reactor.core.publisher.Mono; // 示例调用逻辑 Mono<String> logIdMono = customWebClient.get() .uri("第三方接口请求地址") .exchangeToMono(clientResponse -> { // 读取自定义头中的原始原因短语,兜底用默认原因短语 String reasonPhrase = clientResponse.headers() .header("X-Custom-Status-Reason") .stream() .findFirst() .orElse(clientResponse.statusCode().getReasonPhrase()); // 正则提取LogId String logId = null; Pattern logIdPattern = Pattern.compile("LogId=(\\w+)"); Matcher matcher = logIdPattern.matcher(reasonPhrase); if (matcher.find()) { logId = matcher.group(1); } // 后续业务处理逻辑 return Mono.justOrEmpty(logId); });
补充说明
- 若使用Jetty、OkHttp等其他底层客户端,可沿用相同思路:拦截底层原生响应对象,获取原始原因短语后传递到上层ClientResponse
- Spring 6+/Spring Boot 3+ 暂未新增直接获取原因短语的上层API,上述方案依然适用
- 若原因短语包含中文或特殊字符,可存入响应头前做UTF-8编码,上层读取后再解码避免乱码
内容的提问来源于stack exchange,提问作者Timo
相关产品推荐
相关产品推荐

