java 11 HTTP 客户端上的“java.io.IOException:连接超时”VS HttpTimeoutException

use*_*421 5 java timeoutexception java-http-client java-11

我正在使用 Java 11 http-client ( java.net.http)。

send()方法声明了这些异常:

@throws IOException
@throws InterruptedException
@throws IllegalArgumentException
@throws SecurityException
Run Code Online (Sandbox Code Playgroud)

我对捕获超时引起的异常感兴趣。我认为最好的方法是抓住 HttpTimeoutException(扩展IOException

但是,我有时会看到,当发生超时时,引发的异常是:

java.io.IOException: Connection timed out
Run Code Online (Sandbox Code Playgroud)

现在我想知道:

  1. 为什么会抛出更一般的异常?
  2. 应该如何编写 catch 以确保捕获所有可能的超时相关异常?

小智 0

@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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请参阅下面的方法,它是 HttpClientImpl.java 的内部方法。处理您想要管理的所有异常,然后您就可以实现您的代码。

如果您处理 HttpConnectTimeoutException、IOException、HttpTimeoutException,那么您就可以了。