HTTP响应内容读取后:是否需关闭Reader?EntityUtils.consume是否足够?
Great question! Let’s break this down clearly:
Short Answer
You don’t strictly need to call reader.close() if you’re already using EntityUtils.consume(entity), but combining proper resource management (like closing the Reader) with EntityUtils.consume is the safest approach. Here’s why:
What Each Method Does
Closing the Reader: When you create a
Readerwrappingentity.getContent(), closing it will cascade down to close the underlyingInputStreamfrom the HTTP entity. This releases immediate resources tied to that stream. However, if an exception is thrown while closing the Reader (unlikely but possible), subsequent code (likeEntityUtils.consume) won’t run, leaving the entity’s resources potentially unhandled.EntityUtils.consume(entity): This Apache HttpClient utility method is specifically designed to clean up HTTP entity resources. It will:
- Read any remaining content from the entity’s stream (critical for reusing the HTTP connection, if your connection manager supports it).
- Close the underlying
InputStreamregardless of whether you’ve read all the content.
Even if you’ve already read the entire content with
IOUtils.toString(reader),EntityUtils.consumewill ensure the stream is closed properly.
Best Practice
The safest way is to use try-with-resources for the Reader (which automatically closes it, even if an exception occurs) and still call EntityUtils.consume to ensure full cleanup. Here’s how to adjust your code:
HttpEntity entity = response.getEntity(); if (entity == null) { // handle null entity case } String content; try (Reader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"))) { content = IOUtils.toString(reader); } catch (IOException e) { // handle reading exception } finally { try { EntityUtils.consume(entity); } catch (IOException e) { // log or handle cleanup exception } }
Why this works:
- The try-with-resources block guarantees the Reader (and its underlying streams) are closed, even if
IOUtils.toStringthrows an exception. - The
finallyblock ensuresEntityUtils.consumeruns no matter what, handling edge cases like unclosed streams or remaining content needed for connection reuse.
What If I Skip reader.close()?
If you omit reader.close() and only call EntityUtils.consume(entity), it will still close the underlying stream. However, leaving the Reader open until EntityUtils.consume is called could hold onto resources longer than necessary, and if EntityUtils.consume is never executed (e.g., an exception before that line), you risk resource leaks.
内容的提问来源于stack exchange,提问作者ru51an

