《HttpClient官方文檔》2.6 連接維持存活策略
2.6. 連接維持存活策略
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();
最後更新:2017-05-19 12:05:09