gpt4 book ai didi

java - keep-alive 是否始终在使用 httpclient 的请求中发送以及如何防止发送它

转载 作者:行者123 更新时间:2023-12-02 05:32:17 28 4
gpt4 key购买 nike

我有一个 Java/Spring 项目,我在其中使用 Oauth2RestTemplate 并使其使用 HttpClient (org.apache.http.client.Httpclient) 而不是默认的 SimpleClient

HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); 

HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
oAuth2RestTemplate.setRequestFactory(requestFactory);

就此而言,我想知道/了解是否始终为所有请求发送 keep-alive header ?

如果一直发送,有办法禁止发送吗?我看到一个帖子 - Disable Keep Alive in Apache HttpClient谈到禁用它,但它建议对 httpMethod 进行设置。我不确定如何在上面描述的代码设置中访问此 httpMethod。

最佳答案

使用仅返回 false 的 keepAlive() 方法实现 ConnectionReuseStrategy。请参阅 HttpClientBuilder 中的 setConnectionReuseStrategy()

您可能还想发送一个值为 closeConnection header 。

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 header

当大多数人说 keep-alive header 时,他们通常指的是一个名为 Connection 的不同 header 。这两个 header 一起工作:

HTTP/1.1 200 OK
...
Connection: Keep-Alive
Keep-Alive: timeout=5, max=1000
...

Connection header 暗示应重新使用连接。 Keep-Alive header 指定连接应保持打开状态的最短时间,以及连接可重复使用的最大请求数。

Connection header 的常见值为 keep-aliveclose。服务器和客户端都可以发送此 header 。如果 Connection header 设置为 close,则忽略 Keep-Alive header 。

<强>2。 HTTP/1.1 和 HTTP/2

对于 HTTP/1.1,默认情况下连接是持久的。尽管许多服务器仍然发送它们以实现向后兼容性,但 Keep-Alive header 已被弃用(HTTP 规范中不再定义)。

无法处理 HTTP/1.1 持久连接的客户端应设置一个值为 closeConnection header 。

HTTP/2 使用多路复用; ConnectionKeep-Alive header 均不应与 HTTP/2 一起使用。

<强>3。代理和缓存的影响

一般来说,持久连接不能通过非透明代理工作。他们会默默地删除任何 ConnectionKeep-Alive header 。

<强>4。连接处理

由于持久连接现在是 HTTP/1.1 的默认设置,因此我们需要一种机制来控制何时/如何使用它们。对于 Apache http 客户端,ConnectionReuseStrategy 确定连接是否应持久,而 ConnectionKeepAliveStrategy 指定连接可重用的最大空闲时间。

关于java - keep-alive 是否始终在使用 httpclient 的请求中发送以及如何防止发送它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56194382/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com