使用仅返回 false 的 keepAlive() 方法实现 ConnectionReuseStrategy。请参阅HttpClientBuilder 中的setConnectionReuseStrategy()。
您可能还想发送一个值为close 的Connection 标头。
https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/ConnectionReuseStrategy.html
例子:
List<Header> headers = new ArrayList<>();
headers.add(new BasicHeader(HttpHeaders.CONNECTION, "close"));
HttpClientBuilder builder = HttpClients.custom().setDefaultHeaders(headers)
.setConnectionReuseStrategy(
new ConnectionReuseStrategy() {
@Override
public boolean keepAlive(HttpResponse httpResponse, HttpContext httpContext) {
log.info("**** keepAlive strategy returning false");
return false;
}
});
CloseableHttpClient httpClient = builder.build();
HttpGet httpGet = new HttpGet("https://google.com");
CloseableHttpResponse response = httpClient.execute(httpGet);
log.info("Response status: " + response.getStatusLine());
response.close();
一些附加信息:
1. Keep-Alive 标头
当大多数人说keep-alive 标头时,他们通常指的是另一个称为Connection 的标头。这两个标题一起工作:
HTTP/1.1 200 OK
...
Connection: Keep-Alive
Keep-Alive: timeout=5, max=1000
...
Connection 标头暗示应该重新使用连接。 Keep-Alive 标头指定连接应保持打开的最短时间,以及连接可重复使用的最大请求数。
Connection 标头的常见值为 keep-alive 和 close。服务器和客户端都可以发送此标头。如果Connection 标头设置为close,则Keep-Alive 标头将被忽略。
2。 HTTP/1.1 和 HTTP/2
使用 HTTP/1.1,默认情况下连接是持久的。 Keep-Alive 标头已被弃用(不再在 HTTP 规范中定义),尽管许多服务器仍然发送它们以实现向后兼容性。
无法处理 HTTP/1.1 持久连接的客户端应设置 Connection 标头,其值为 close。
HTTP/2 使用多路复用; Connection 和 Keep-Alive 标头都不应该与 HTTP/2 一起使用。
3.代理和缓存的影响
一般来说,持久连接不能通过非透明代理工作。他们会默默地删除任何 Connection 或 Keep-Alive 标头。
4.连接处理
由于持久连接现在是 HTTP/1.1 的默认设置,因此我们需要一种机制来控制何时/如何使用它们。对于 Apache http 客户端,ConnectionReuseStrategy 确定连接是否应该是持久的,而ConnectionKeepAliveStrategy 指定连接可重用的最大空闲时间。