在我的測試應用程序,我執行連續HTTPGET請求到同一個主機與的Apache的HttpClient但在每次下一個請求事實證明,以前的HttpConnection被關閉,新的HttpConnection創建。如何獲得與Apache HttpClient的持久HttpConnection?
我使用HttpClient的同一個實例並且不關閉響應。從每個實體我得到InputStream,用掃描儀讀取它,然後關閉掃描儀。我測試了KeepAliveStrategy,它返回true。請求之間的時間不超過keepAlive或connectionTimeToLive持續時間。
有誰能告訴我可能是什麼原因導致這種行爲?
更新
我已經找到了解決辦法。爲了使HttpConnecton保持活動狀態,需要在構建HttpClient時設置HttpClientConnectionManager。我已經使用BasicHttpClientConnectionManager。
ConnectionKeepAliveStrategy keepAliveStrat = new DefaultConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context)
{
long keepAlive = super.getKeepAliveDuration(response, context);
if (keepAlive == -1)
keepAlive = 120000;
return keepAlive;
}
};
HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
try (CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(connectionManager) // without this setting connection is not kept alive
.setDefaultCookieStore(store)
.setKeepAliveStrategy(keepAliveStrat)
.setConnectionTimeToLive(120, TimeUnit.SECONDS)
.setUserAgent(USER_AGENT)
.build())
{
HttpClientContext context = new HttpClientContext();
RequestConfig config = RequestConfig.custom()
.setCookieSpec(CookieSpecs.DEFAULT)
.setSocketTimeout(10000)
.setConnectTimeout(10000)
.build();
context.setRequestConfig(config);
HttpGet httpGet = new HttpGet(uri);
CloseableHttpResponse response = httpClient.execute(httpGet, context);
HttpConnection conn = context.getConnection();
HttpEntity entity = response.getEntity();
try (Scanner in = new Scanner(entity.getContent(), ENC))
{
// do something
}
System.out.println("open=" + conn.isOpen()); // now open=true
HttpGet httpGet2 = new HttpGet(uri2); // on the same host with other path
// and so on
}
更新2
一般檢查連接與conn.isOpen()
是不檢查的連接狀態,因爲正確的方法:「內部HTTP連接管理器與作爲代理一個真正ManagedHttpClientConnection的情況下工作連接管理連接狀態並控制I/O操作的執行如果託管連接被釋放或被其消費者明確關閉,則底層連接從其代理中分離出來並返回給管理器即使服務使用者stil l持有對代理實例的引用,它不再能夠有意或無意地執行任何I/O操作或更改真實連接的狀態。「(HttpClent Tutorial)
正如@oleg指出的那樣,跟蹤連接的正確方法是使用logger。
你能告訴我們一些代碼嗎? – inovaovao
是的。我已經添加了該代碼。 – snptc