簡體   English   中英

為什么Apache CloseableHttpResponse在關閉時不使用該實體?

[英]Why does Apache CloseableHttpResponse not consume the entity on close?

查看快速入門指南,它提供以下代碼示例:

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://targethost/homepage");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
// the user MUST call CloseableHttpResponse#close() from a finally clause.
// Please note that if response content is not fully consumed the underlying
// connection cannot be safely re-used and will be shut down and discarded
// by the connection manager. 
try {
    System.out.println(response1.getStatusLine());
    HttpEntity entity1 = response1.getEntity();
    // do something useful with the response body
    // and ensure it is fully consumed
    EntityUtils.consume(entity1);
} finally {
    response1.close();
}

上面代碼中的兩個注釋說,我們必須關閉響應對象

“正確重新分配系統資源”

“如果響應內容未被完全消耗,則基礎連接將無法安全地重用,並且將被連接管理器關閉並丟棄”。

現在,Apache非常友好地為我們實現了CloseableHttpResponse,這意味着我們可以使用try-with-resources塊。 但是close方法僅關閉響應對象,為什么它還不消耗實體?

因為此時很難說出調用方是否打算重用基礎連接。 在某些情況下,可能只想從較大的響應主體中讀取一小塊,然后立即終止連接。

換句話說,同一件事一遍又一遍地發生:沒有一種方法可以使每個人都快樂。

該代碼段將在嘗試使基礎連接保持活動狀態的同時,確保正確分配資源。

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://targethost/homepage");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try {
    System.out.println(response1.getStatusLine());
} finally {
    EntityUtils.consume(response1.getEntity());
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM