HTTP规范不会指定长连接存活的时间,以及是否应该维持连接。一些HTTP服务器使用非标准的“Keep-Alive”头部来与客户端通信,以维持连接在服务器端存活的时间(以秒为单位)。如果这个可用, HttpClient将利用它。如果响应中不存在“Keep-Alive”头部,则HttpClient假定连接可以无限期存活。然而,通常许多HTTP服务器在使用中配置为不通知客户端,长连接在闲置一定时期之后会被丢弃,以便节省系统资源。 万一默认策略导致结果过于乐观,可能需要提供维持一个自定义的存活策略。
ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { // Honor 'keep-alive' header HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { try { return Long.parseLong(value) * 1000; } catch(NumberFormatException ignore) { } } } HttpHost target = (HttpHost) context.getAttribute( HttpClientContext.HTTP_TARGET_HOST); if ("www.naughty-server.com".equalsIgnoreCase(target.getHostName())) { // Keep alive for 5 seconds only return 5 * 1000; } else { // otherwise keep alive for 30 seconds return 30 * 1000; } } }; CloseableHttpClient client = HttpClients.custom() .setKeepAliveStrategy(myStrategy) .build();
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/114014.html