如何解决“ java.io.IOException:连接超时” VS java 11 HTTP Client上的HttpTimeoutException
我正在使用Java 11 http-client(java.net.http
)。
send()
方法声明以下异常:
@throws IOException
@throws InterruptedException
@throws IllegalArgumentException
@throws SecurityException
我有兴趣捕获由超时引起的异常。
我认为最好的方法是赶上
HttpTimeoutException
(扩展IOException
)
但是,有时我会看到发生超时时抛出的异常是:
java.io.IOException: Connection timed out
现在我想知道:
- 为什么会引发更一般的异常?
- 如何编写捕获以确保捕获到所有可能的超时相关异常?
解决方法
@Override
public <T> HttpResponse<T>
send(HttpRequest req,BodyHandler<T> responseHandler)
throws IOException,InterruptedException
{
CompletableFuture<HttpResponse<T>> cf = null;
try {
cf = sendAsync(req,responseHandler,null,null);
return cf.get();
} catch (InterruptedException ie) {
if (cf != null )
cf.cancel(true);
throw ie;
} catch (ExecutionException e) {
final Throwable throwable = e.getCause();
final String msg = throwable.getMessage();
if (throwable instanceof IllegalArgumentException) {
throw new IllegalArgumentException(msg,throwable);
} else if (throwable instanceof SecurityException) {
throw new SecurityException(msg,throwable);
} else if (throwable instanceof HttpConnectTimeoutException) {
HttpConnectTimeoutException hcte = new HttpConnectTimeoutException(msg);
hcte.initCause(throwable);
throw hcte;
} else if (throwable instanceof HttpTimeoutException) {
throw new HttpTimeoutException(msg);
} else if (throwable instanceof ConnectException) {
ConnectException ce = new ConnectException(msg);
ce.initCause(throwable);
throw ce;
} else if (throwable instanceof SSLHandshakeException) {
// special case for SSLHandshakeException
SSLHandshakeException he = new SSLHandshakeException(msg);
he.initCause(throwable);
throw he;
} else if (throwable instanceof SSLException) {
// any other SSLException is wrapped in a plain
// SSLException
throw new SSLException(msg,throwable);
} else if (throwable instanceof IOException) {
throw new IOException(msg,throwable);
} else {
throw new IOException(msg,throwable);
}
}
}
请参见下面的方法,该方法是HttpClientImpl.java的内部方法。 处理所有要管理的异常,因此可以实现代码。
如果您处理HttpConnectTimeoutException,IOException,HttpTimeoutException,那么您会被覆盖。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。