JAVA-5484: New Java Http Client Timeout (#12223)

Co-authored-by: Harpal Singh <harpal.singh@kaleyra.com>
This commit is contained in:
Harry9656 2022-05-19 01:34:23 +02:00 committed by GitHub
parent 67303db98b
commit 75a751df3a
2 changed files with 66 additions and 0 deletions

View File

@ -0,0 +1,12 @@
package com.baeldung.http;
import java.net.http.HttpClient;
import java.time.Duration;
public class JavaHttpClientTimeout {
static HttpClient getHttpClientWithTimeout(int seconds) {
return HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(seconds))
.build();
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.http;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpConnectTimeoutException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static com.baeldung.http.JavaHttpClientTimeout.getHttpClientWithTimeout;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class JavaHttpClientTimeoutIntegrationTest {
private HttpClient httpClient;
private HttpRequest httpRequest;
@BeforeEach
public void setUp() {
httpClient = getHttpClientWithTimeout(3);
httpClient.connectTimeout().map(Duration::toSeconds)
.ifPresent(sec -> System.out.println("Timeout in seconds: " + sec));
httpRequest = HttpRequest.newBuilder().uri(URI.create("http://10.255.255.1")).GET().build();
}
@Test
void shouldThrowExceptionWhenMakingSyncCall() {
HttpConnectTimeoutException thrown = assertThrows(
HttpConnectTimeoutException.class,
() -> httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()),
"Expected doThing() to throw, but it didn't"
);
assertTrue(thrown.getMessage().contains("timed out"));
}
@Test
void shouldThrowExceptionWhenMakingASyncCall() throws ExecutionException, InterruptedException, TimeoutException {
CompletableFuture<String> completableFuture =
httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.exceptionally(Throwable::getMessage);
String response = completableFuture.get(5, TimeUnit.SECONDS);
assertTrue(response.contains("timed out"));
}
}