From 8f54543306578e62d539fdc0811fdd4044d1732e Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Mon, 23 May 2022 18:27:46 +0200 Subject: [PATCH] JAVA-5484: Added Java Http Request Timeout (#12248) Co-authored-by: Harpal Singh --- ...ClientTimeoutOnRequestIntegrationTest.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 core-java-modules/core-java-networking-3/src/test/java/com/baeldung/http/JavaHttpClientTimeoutOnRequestIntegrationTest.java diff --git a/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/http/JavaHttpClientTimeoutOnRequestIntegrationTest.java b/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/http/JavaHttpClientTimeoutOnRequestIntegrationTest.java new file mode 100644 index 0000000000..d693b9075c --- /dev/null +++ b/core-java-modules/core-java-networking-3/src/test/java/com/baeldung/http/JavaHttpClientTimeoutOnRequestIntegrationTest.java @@ -0,0 +1,51 @@ +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.time.LocalTime; + +import static com.baeldung.http.JavaHttpClientTimeout.getHttpClientWithTimeout; +import static java.time.LocalTime.now; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class JavaHttpClientTimeoutOnRequestIntegrationTest { + + 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")) + .timeout(Duration.ofSeconds(1)) + .GET() + .build(); + } + + @Test + void shouldThrowExceptionWhithin1SecondWhenMakingSyncCall() { + LocalTime beforeHttpCall = now(); + HttpConnectTimeoutException thrown = assertThrows( + HttpConnectTimeoutException.class, + () -> httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()), + "Expected doThing() to throw, but it didn't" + ); + LocalTime afterHttpCall = now(); + assertTrue(thrown.getMessage().contains("timed out")); + assertEquals(1, Duration.between(beforeHttpCall, afterHttpCall).getSeconds()); + } + +}