Timeouts in java.net.http.HttpClient not working as expected

Viewed 3110

Java Http client with 100ms timeout throws Timeout exception when connecting to an API.

  1. I have verified that api responds within 10ms with a curl call.

    curl --max-time 0.01 http://localhost:8000/

    @Test
    public void testHTTPClient() throws URISyntaxException, IOException, InterruptedException {


        HttpClient client = HttpClient.newBuilder().build().newHttpClient();
        java.net.URI uri = new URI("http://localhost:8000/");
        HttpRequest req = HttpRequest.newBuilder(uri).GET().timeout(Duration.ofMillis(100)).build();
        long start = Instant.now().toEpochMilli();
        try {
            java.net.http.HttpResponse<String> response = client.send(req, java.net.http.HttpResponse.BodyHandlers.ofString());
            System.out.println(response.body());
        } catch (HttpTimeoutException e) {
            System.out.println("Time taken " + (Instant.now().toEpochMilli() - start));
            e.printStackTrace();
        }

    }

I am expecting the output printed to the screen. But I get the following exception.

Time taken 159

java.net.http.HttpTimeoutException: request timed out
    at java.net.http/jdk.internal.net.http.HttpClientImpl.send(HttpClientImpl.java:559)
    at java.net.http/jdk.internal.net.http.HttpClientFacade.send(HttpClientFacade.java:119)

When I run the test multiple times with the 100ms timeout. Few instances have a successful response. With a larger timeout like 150ms, I haven't faced the timeout exception.

0 Answers
Related