Java 当我们在JAX-RS中直接获取http主体时,如何关闭响应对象?
当我们用jersey编写REST客户端时,应该关闭Java 当我们在JAX-RS中直接获取http主体时,如何关闭响应对象?,java,jersey,jax-rs,jersey-client,Java,Jersey,Jax Rs,Jersey Client,当我们用jersey编写REST客户端时,应该关闭Response,如下所示: Client c = ClientBuilder.newClient(); Response r = null; try { r = c.target("http://localhost:8080/testrest/customers/854878").request().get(); Customer cus = r.readEntity(Customer.class); /* proc
Response
,如下所示:
Client c = ClientBuilder.newClient();
Response r = null;
try {
r = c.target("http://localhost:8080/testrest/customers/854878").request().get();
Customer cus = r.readEntity(Customer.class);
/* process result */
} catch (Exception e) {
/* log here */
if (r != null) {
r.close();
}
}
当我们直接读取HTTP正文时,应该如何访问Response
对象:
Client c = ClientBuilder.newClient();
Customer cus = c.target("http://localhost:8080/testrest/customers/854878").request().get(Customer.class);
/* close Response object and process result */
客户端有一个close方法。调查其来源。如果Client.close未清理其资源,则必须获取响应的引用并将其关闭。否则你会有悬而未决的联系。
如果代码允许你做某事,并不意味着你应该这样做。但是从您的问题中,我推断您理解它。假设您使用的是Glassfish的
jersey客户端
实现版本2.3.1(),那么您可以跟踪发出的呼叫。再往下走一点,你
其中,t
是基于指定的类
对象创建的对象
API本身似乎没有说明这一点,因此实现不必关闭底层响应流。我能找到的唯一东西是从Client
javadoc
在将客户端实例释放到之前,必须正确关闭客户端实例
避免泄漏资源
因此,不要依赖于特定的实现,确保自己关闭所有东西,即使这意味着您必须中断Fluent方法调用并将中间对象引用存储在变量中
org.glassfish.jersey.message.internal.InboundMessageContext#readEntity(Class<T>, Type, Annotation[], PropertiesDelegate)
if (!buffered && !(t instanceof Closeable) && !(t instanceof Source)) {
entityContent.close(); // wrapper to the actual response stream
}