1. 概述
本教程将演示如何使用 Apache HttpClient 取消 HTTP 请求。这个技巧在处理长时间运行的请求或下载大文件时特别实用,能有效避免不必要的带宽和连接消耗。
想深入探索 HttpClient 的其他高级用法?可以参考 **HttpClient 核心教程**。
2. 取消 GET 请求
要中止正在进行的请求,只需调用:
request.abort();
这能确保客户端无需读取完整的响应体即可释放连接:
@Test
void whenRequestIsCanceled_thenCorrect() throws IOException {
HttpGet request = new HttpGet(SAMPLE_URL);
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
httpClient.execute(request, response -> {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getCode());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
System.out.println("----------------------------------------");
if (entity != null) {
// 关闭流并释放系统资源
entity.close();
}
// 不想读取响应体?直接取消请求
request.abort();
assertThat(response.getCode()).isEqualTo(HttpStatus.SC_OK);
return response;
});
}
}
⚠️ 关键点:
abort()
会立即终止请求,无需等待响应体传输完成- 务必在取消前关闭实体流(
entity.close()
),避免资源泄漏
3. 取消 GET 请求(HttpClient 4.5 版本)
HttpClient 4.5 的实现略有不同,注意资源释放方式:
@Test
public final void whenRequestIsCanceled_thenCorrect() throws IOException {
instance = HttpClients.custom().build();
final HttpGet request = new HttpGet(SAMPLE_URL);
response = instance.execute(request);
try {
final HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
System.out.println("----------------------------------------");
// 不想读取响应体?直接取消请求
request.abort();
} finally {
response.close(); // 必须在 finally 块中关闭响应
}
}
✅ 最佳实践:
- 使用
try-finally
确保响应对象被正确关闭 - 即使取消请求,也要释放底层连接资源
4. 总结
本文展示了通过 HttpClient 取消请求的两种方式。对于长时间运行的请求,另一种控制手段是设置合理的超时时间。
所有示例代码可在 GitHub 项目 中获取(基于 Eclipse,可直接导入运行)。HttpClient 4.x 的代码片段请参考 **HttpClient 4 模块**。