Contents

Apache HTTPClient 取消请求

1. 概述

本快速教程展示了如何使用 Apache HttpClient 取消 HTTP 请求

这对于可能长时间运行的请求或大型下载文件特别有用,否则会不必要地消耗带宽和连接。

如果您想更深入地挖掘并学习可以使用 HttpClient 做的其他很酷的事情 - 前往**HttpClient 教程 **。

2. 中止 GET 请求

要中止正在进行的请求,客户端可以简单地使用:

request.abort();

这将确保客户端不必消耗整个请求体来释放连接:

@Test
public void whenRequestIsCanceled_thenCorrect() 
  throws ClientProtocolException, IOException {
    HttpClient instance = HttpClients.custom().build();
    HttpGet request = new HttpGet(SAMPLE_URL);
    HttpResponse response = instance.execute(request);
    try {
        System.out.println(response.getStatusLine());
        request.abort();
    } finally {
        response.close();
    }
}