From 73e72f226845c790e4a6e6dccaed50ee32791f45 Mon Sep 17 00:00:00 2001 From: Oleg Kalnichevski Date: Sat, 26 Feb 2022 14:54:26 +0100 Subject: [PATCH] HTTPCLIENT-2206: Corrected resource de-allocation by fluent response objects --- .../apache/http/client/fluent/Response.java | 27 ++++++++++++------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/fluent-hc/src/main/java/org/apache/http/client/fluent/Response.java b/fluent-hc/src/main/java/org/apache/http/client/fluent/Response.java index 76a6a98cf..61e1c1a2c 100644 --- a/fluent-hc/src/main/java/org/apache/http/client/fluent/Response.java +++ b/fluent-hc/src/main/java/org/apache/http/client/fluent/Response.java @@ -26,6 +26,7 @@ */ package org.apache.http.client.fluent; +import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -116,20 +117,26 @@ public class Response { public void saveContent(final File file) throws IOException { assertNotConsumed(); - final StatusLine statusLine = response.getStatusLine(); - if (statusLine.getStatusCode() >= 300) { - throw new HttpResponseException(statusLine.getStatusCode(), - statusLine.getReasonPhrase()); - } - final FileOutputStream out = new FileOutputStream(file); try { - final HttpEntity entity = this.response.getEntity(); - if (entity != null) { - entity.writeTo(out); + final StatusLine statusLine = response.getStatusLine(); + if (statusLine.getStatusCode() >= 300) { + throw new HttpResponseException(statusLine.getStatusCode(), + statusLine.getReasonPhrase()); + } + final FileOutputStream out = new FileOutputStream(file); + try { + final HttpEntity entity = this.response.getEntity(); + if (entity != null) { + entity.writeTo(out); + } + } finally { + out.close(); } } finally { this.consumed = true; - out.close(); + if (this.response instanceof Closeable) { + ((Closeable) this.response).close(); + } } }