是否始终使用httpclient发出保持活动请求,以及如何阻止发送该请求

时间:2019-05-17 22:41:55

标签: java spring httpclient keep-alive

我有一个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);

对此,我想知道/了解是否始终为所有请求发送保持活动报头?

如果始终发送,是否可以禁用发送?我看到一则帖子Disable Keep Alive in Apache HttpClient讨论了如何禁用它,但它在httpMethod上提出了一个设置。我不确定如何在上述代码设置中访问此httpMethod。

1 个答案:

答案 0 :(得分:0)

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

您可能还希望发送一个值为Connection的{​​{1}}标头。

https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/ConnectionReuseStrategy.html

示例:

close

一些其他信息:

1。 Keep-Alive标头

大多数人说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(); 标头时,通常是指另一个名为keep-alive的标头。这两个标头协同工作:

Connection

HTTP/1.1 200 OK ... Connection: Keep-Alive Keep-Alive: timeout=5, max=1000 ... 标头表明应该重新使用该连接。 Connection标头指定连接应保持打开状态的最短时间,以及可以重新使用该连接的最大请求数。

Keep-Alive标头的公用值为Connectionkeep-alive。服务器和客户端都可以发送此标头。如果close标头设置为Connection,则close标头将被忽略。

2。 HTTP / 1.1和HTTP / 2

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

无法处理HTTP / 1.1持久连接的客户端应将Keep-Alive标头设置为值Connection

HTTP / 2使用多路复用; closeConnection标头都不能与HTTP / 2一起使用。

3。代理和缓存的作用

通常来说,持久连接无法通过非透明代理起作用。他们会静默删除任何Keep-AliveConnection标头。

4。连接处理

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