我使用Jersey-Client检查服务器资源的可用性:
public class Test{
private final Client client=...;
public void test(URI myURL){
try {
final WebTarget functionConCheck = client.target(myURL);
final Response resp = functionConCheck.request(MediaType.APPLICATION_JSON).head();
try {
if (resp.getStatus() == Status.OK.getStatusCode()) {
System.out.println("OK");
}
} finally {
resp.close();
}
} catch (MalformedURLException | URISyntaxException ex) {
LOGGER.error("Error checking", ex);
} catch (final ProcessingException e) {
LOGGER.error("No network connection", e);
}
}
}
但代码抛出异常:
ERROR [] ? (:) - No network connection
javax.ws.rs.ProcessingException: java.net.SocketException: Socket closed
at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:287) ~[jersey-client-2.22.1.jar:?]
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:255) ~[jersey-client-2.22.1.jar:?]
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:684) ~[jersey-client-2.22.1.jar:?]
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:681) ~[jersey-client-2.22.1.jar:?]
at org.glassfish.jersey.internal.Errors.process(Errors.java:315) ~[jersey-common-2.22.1.jar:?]
at org.glassfish.jersey.internal.Errors.process(Errors.java:297) ~[jersey-common-2.22.1.jar:?]
at org.glassfish.jersey.internal.Errors.process(Errors.java:228) ~[jersey-common-2.22.1.jar:?]
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444) ~[jersey-common-2.22.1.jar:?]
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:681) ~[jersey-client-2.22.1.jar:?]
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:411) ~[jersey-client-2.22.1.jar:?]
at org.glassfish.jersey.client.JerseyInvocation$Builder.head(JerseyInvocation.java:375) ~[jersey-client-2.22.1.jar:?]
Caused by: java.net.SocketException: Socket is closed
at java.net.Socket.getInputStream(Unknown Source) ~[?:1.7.0_80]
at sun.security.ssl.SSLSocketImpl.doneConnect(Unknown Source) ~[?:1.7.0_80]
at sun.security.ssl.SSLSocketImpl.<init>(Unknown Source) ~[?:1.7.0_80]
at sun.security.ssl.SSLSocketFactoryImpl.createSocket(Unknown Source) ~[?:1.7.0_80]
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source) ~[?:1.7.0_80]
at sun.net.www.http.HttpClient.parseHTTP(Unknown Source) ~[?:1.7.0_80]
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) ~[?:1.7.0_80]
at java.net.HttpURLConnection.getResponseCode(Unknown Source) ~[?:1.7.0_80]
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source) ~[?:1.7.0_80]
at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:394) ~[jersey-client-2.22.1.jar:?]
at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:285) ~[jersey-client-2.22.1.jar:?]
永远不会在任何地方调用{p> client.close()
。唯一关闭的是response
,但每个方法调用都有一个新的响应实例。
这个例外来自哪里以及如何避免它?