I am using Jersey client for REST calls from Java code:
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.22.1</version>
</dependency>
In my GET request,
javax.ws.rs.client.Invocation.Builder builder = ClientBuilder.newClient().target(url).request();
builder.get().readEntity(String.class);
the client will be closed automatically after calling readEntity(String.class)
.
If I use,
builder.get(String.class);
I get the same output.
Is the connection closed automatically or do I need to close it manually in this case?
Short answer
Consider the following code:
Under the hood, Jersey invokes
Response#readEntity(Class<T>)
if the request has succeeded and the connection will be closed for you. So the connection doesn't need to be closed manually in this situation.Now consider the following code:
For this situation, you need to invoke
Response#close()
to close the connection. Or invokeResponse#readEntity(Class<T>)
to make Jersey close the connection for you.Long answer
As stated in the documentation, if you don't read the entity, then you need to close the response manually by invoking
Response#close()
.For more details, have a look at Jersey's documentation about how to close connections:
Additionally, have a look at
JerseyInvocation
source. The most important parts are quoted below.In the
translate(ClientResponse, RequestScope, Class<T>)
method you'll see thatresponse.readEntity(Class<T>)
is invoked.JerseyInvocation.Builder#get(Class<T>)
Invoke HTTP
GET
method for the current request synchronously.JerseyInvocation.Builder#method(String, Class<T>)
Invoke an arbitrary method for the current request synchronously.
JerseyInvocation#invoke(Class<T>)
Synchronously invoke the request and receive a response of the specified type back.
JerseyInvocation#translate(ClientResponse, RequestScope, Class<T>)
If the request suceeded, the response entity is read as an instance of specified Java type using
Response#readEntity(Class<T>)
: