1. 概述
本文将讲解如何配置 Apache HttpClient 禁用自动重定向功能。
根据 HTTP 规范,HttpClient 默认会自动跟随重定向。这在某些场景下很方便,但有时我们需要控制重定向行为——比如需要获取原始响应状态码或自定义重定向逻辑。本文将介绍如何修改默认配置,彻底关闭自动重定向功能。
如果想深入学习 HttpClient 的其他高级用法,可以参考 **HttpClient 完全指南**。
2. 禁用重定向功能
2.1. HttpClient 5 配置方案
@Test
void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
final HttpGet request = new HttpGet("http://t.co/I5YYd9tddw");
try (CloseableHttpClient httpClient = HttpClients.custom()
.disableRedirectHandling() // 关键配置:禁用重定向
.build()) {
httpClient.execute(request, response -> {
assertThat(response.getCode(), equalTo(301)); // 验证返回原始 301 状态码
return response;
});
}
}
⚠️ 注意点:
disableRedirectHandling()
是核心方法,直接关闭自动重定向- 测试用例验证了返回的是 301( Moved Permanently)而非重定向后的 200
- 记得使用 try-with-resources 管理 HttpClient 资源
2.2. HttpClient 4.5 配置方案
@Test
void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException {
CloseableHttpClient instance = HttpClients.custom()
.disableRedirectHandling() // 同样的禁用方法
.build();
final HttpGet httpGet = new HttpGet("http://t.co/I5YYd9tddw");
CloseableHttpResponse response = instance.execute(httpGet);
assertThat(response.getStatusLine().getStatusCode(), equalTo(301)); // 4.5 版本的状态码获取方式
}
✅ 关键差异:
- 4.5 版本通过
getStatusLine().getStatusCode()
获取状态码 - 核心配置方法
disableRedirectHandling()
与 5.x 版本完全一致 - 资源管理需要显式调用
response.close()
(建议用 try-with-resources)
3. 总结
本文通过两个版本的实际案例,演示了彻底禁用 Apache HttpClient 自动重定向的标准方案。核心要点:
- 使用
HttpClients.custom().disableRedirectHandling()
创建客户端 - 验证响应状态码确保重定向被禁用(如 301/302 而非 200)
- 不同版本的状态码获取方式略有差异,但核心配置一致
踩坑提醒:禁用重定向后,务必自行处理重定向逻辑,否则可能导致请求失败。常见场景包括:
- 需要记录所有跳转路径
- 防止重定向到恶意网站
- 特定状态码(如 307)的特殊处理