1. Overview
1.概述
This quick tutorial shows how to cancel an HTTP Request with the Apache HttpClient.
这个快速教程展示了如何用Apache HttpClient取消一个HTTP请求。
This is especially useful for potentially long-running requests or large download files that would otherwise unnecessarily consume bandwidth and connections.
这对潜在的长时间运行的请求或大型下载文件特别有用,否则会不必要地消耗带宽和连接。
If you want to dig deeper and learn other cool things you can do with the HttpClient – head on over to the main HttpClient tutorial.
如果你想更深入地了解你可以用HttpClient做的其他很酷的事情–请到主要HttpClient教程。
2. Abort a GET Request
2.中止一个GET请求
To abort an ongoing request, the client can simply use:
要中止一个正在进行的请求,客户可以简单地使用。
request.abort();
This will make sure that the client doesn’t have to consume the entire body of the request to release the connection:
这将确保客户端不必消耗整个请求的主体来释放连接。
@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();
}
}
3. Conclusion
3.结论
This article illustrated how to abort an ongoing request with the HTTP client. Another option to stop long-running requests is to make sure that they will time out.
这篇文章说明了如何用HTTP客户端中止一个正在进行的请求。停止长期运行的请求的另一个选择是确保它们将超时。
The implementation of all these examples and code snippets can be found in my GitHub project – this is an Eclipse-based project, so it should be easy to import and run as it is.
所有这些例子和代码片段的实现可以在我的GitHub项目中找到 – 这是一个基于Eclipse的项目,所以应该很容易导入并按原样运行。