下面列出了怎么用java.net.http.HttpTimeoutException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Sends the http request asynchronously to the API If the request is time out it creates a new
* response object with timeout set to true Otherwise it throws a run time exception
*
* @param request the request to send
* @throws AlgoliaRuntimeException When an error occurred processing the request on the server
* side
*/
public CompletableFuture<HttpResponse> performRequestAsync(@Nonnull HttpRequest request) {
return client
.sendAsync(buildRequest(request), BodyHandlers.ofInputStream())
.thenApply(this::buildResponse)
.exceptionally(
t -> {
if (t.getCause() instanceof HttpConnectTimeoutException
|| t.getCause() instanceof HttpTimeoutException) {
return new HttpResponse(true);
} else if (t.getCause() instanceof SecurityException
|| t.getCause() instanceof IOException
|| t.getCause() instanceof InterruptedException) {
return new HttpResponse().setNetworkError(true);
}
throw new AlgoliaRuntimeException(t);
});
}
@Test
void shouldRetryWithConnectionException() {
assertThat(interceptor.shouldRetry(1, "GET", new HttpTimeoutException("read timeout"))).isTrue();
assertThat(interceptor.shouldRetry(2, "GET", new ConnectException("connection failed"))).isTrue();
assertThat(interceptor.shouldRetry(3, "GET", new ConnectException("connection failed"))).isFalse();
assertThat(interceptor.shouldRetry(1, "GET", new SSLException("Connection reset"))).isTrue();
assertThat(interceptor.shouldRetry(1, "POST", new HttpConnectTimeoutException("connection timeout"))).isTrue();
assertThat(interceptor.shouldRetry(1, "POST", new ConnectException("connection refused"))).isTrue();
/* connect timeout stack trace
Caused by: java.net.SocketTimeoutException: connect timed out
at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
at java.base/java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.base/java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.base/java.net.SocksSocketImpl.connect(Unknown Source)
at java.base/java.net.Socket.connect(Unknown Source)
at okhttp3.internal.platform.Platform.connectSocket(Platform.kt:127)
at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.kt:268)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.kt:176)
at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:236)
at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.kt:109)
*/
assertThat(interceptor.shouldRetry(1, "POST", new SocketTimeoutException("connect timed out"))).isTrue();
}
public static boolean isHttpTimeout(Throwable cause) {
return cause instanceof HttpTimeoutException;
}