1

Do I have to use try-finally to ensure that JAX-RS Response is closed after getting the Response?

Building and Invoking Requests | RESTfu­­l Jav­a­ wit­h ­JAX­-­­RS 2.­0­ (Second Edition) uses try..finally:

Version 1

Response response = client.target("http://commerce.com/customers/123")
                          .accept("application/json")
                          .get();
try {
   if (response.getStatus() == 200) {
      response.bufferEntity();
      Customer customer = response.readEntity(Customer.class);
      Map rawJson = response.readEntity(Map.class);
   }
} finally {
  response.close();
}

I cannot use try-with-resource, as JAX-RS Response does not implement AutoClosable. So why do I have to use try-finally?

Version 2 (without try-finally)

if (response.getStatus() == 200) {
      response.bufferEntity();
      Customer customer = response.readEntity(Customer.class);
      Map rawJson = response.readEntity(Map.class);
}
response.close();

My Question is

The response is also always closed with Version 2, am I right?

Cœur
  • 37,241
  • 25
  • 195
  • 267
nimo23
  • 5,170
  • 10
  • 46
  • 75
  • https://stackoverflow.com/questions/33083961/closing-jax-rs-client-response: So if I use "response.bufferEntity()", then I NEED "try..catch". If I do not need "response.bufferEntity()" and call only "response.getEntity()", then I DO NOT NEED "try..catch", as resource is closed automatically after the first call of "response.getEntity()". Am I right? – nimo23 Aug 06 '17 at 10:36

0 Answers0