Java
HTTP
URL
Ping
Programming

Preferred Java way to ping an HTTP URL for availability

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

If you want to check whether an HTTP endpoint is available from Java, the right tool is an HTTP client, not an ICMP ping. The real question is whether the web service responds within an acceptable timeout and with an acceptable status code.

Define What “Available” Means

Before writing code, decide what counts as success. Common policies are:

  • any 2xx response
  • any 2xx or 3xx response
  • only one specific endpoint returning one expected code

A monitoring check without an explicit status-code policy becomes noisy quickly.

Use Java 11 HttpClient

For modern Java, java.net.http.HttpClient is the preferred built-in API.

java
1import java.io.IOException;
2import java.net.URI;
3import java.net.http.HttpClient;
4import java.net.http.HttpRequest;
5import java.net.http.HttpResponse;
6import java.time.Duration;
7
8public class UrlCheck {
9    public static boolean isAvailable(String url) {
10        HttpClient client = HttpClient.newBuilder()
11                .connectTimeout(Duration.ofSeconds(3))
12                .followRedirects(HttpClient.Redirect.NORMAL)
13                .build();
14
15        HttpRequest request = HttpRequest.newBuilder()
16                .uri(URI.create(url))
17                .timeout(Duration.ofSeconds(5))
18                .method("HEAD", HttpRequest.BodyPublishers.noBody())
19                .build();
20
21        try {
22            HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
23            int code = response.statusCode();
24            return code >= 200 && code < 400;
25        } catch (IOException | InterruptedException e) {
26            if (e instanceof InterruptedException) {
27                Thread.currentThread().interrupt();
28            }
29            return false;
30        }
31    }
32
33    public static void main(String[] args) {
34        System.out.println(isAvailable("https://example.com"));
35    }
36}

This is a good default because it uses timeouts, avoids downloading a response body, and expresses the health policy clearly.

Why HEAD Is a Good Starting Point

HEAD asks the server for headers without a response body, which is usually enough for availability checks.

That reduces overhead compared with a full GET. However, not every server supports HEAD properly.

If an endpoint rejects HEAD, a lightweight GET fallback may be appropriate.

java
1private static HttpResponse<Void> sendWithHeadFallback(HttpClient client, URI uri)
2        throws IOException, InterruptedException {
3
4    HttpRequest head = HttpRequest.newBuilder()
5            .uri(uri)
6            .timeout(Duration.ofSeconds(5))
7            .method("HEAD", HttpRequest.BodyPublishers.noBody())
8            .build();
9
10    HttpResponse<Void> first = client.send(head, HttpResponse.BodyHandlers.discarding());
11    if (first.statusCode() != 405) {
12        return first;
13    }
14
15    HttpRequest get = HttpRequest.newBuilder()
16            .uri(uri)
17            .timeout(Duration.ofSeconds(5))
18            .GET()
19            .build();
20
21    return client.send(get, HttpResponse.BodyHandlers.discarding());
22}

Timeouts Matter More Than People Expect

A health check without explicit connect and request timeouts can hang threads for far too long. Availability checks should usually fail fast.

That is why the example configures both:

  • 'connectTimeout on the client'
  • per-request timeout on the request

Without those, a slow or half-broken endpoint can consume resources far longer than intended.

Use Async for Many URLs

If you need to check many endpoints, use sendAsync instead of sequential blocking calls.

java
1import java.net.URI;
2import java.net.http.*;
3import java.time.Duration;
4import java.util.List;
5import java.util.concurrent.CompletableFuture;
6
7HttpClient client = HttpClient.newBuilder()
8        .connectTimeout(Duration.ofSeconds(3))
9        .build();
10
11List<String> urls = List.of("https://example.com", "https://httpbin.org/status/503");
12
13List<CompletableFuture<Void>> futures = urls.stream().map(url -> {
14    HttpRequest request = HttpRequest.newBuilder()
15            .uri(URI.create(url))
16            .timeout(Duration.ofSeconds(5))
17            .GET()
18            .build();
19
20    return client.sendAsync(request, HttpResponse.BodyHandlers.discarding())
21            .thenAccept(resp -> System.out.println(url + " -> " + resp.statusCode()))
22            .exceptionally(ex -> {
23                System.out.println(url + " -> error: " + ex.getMessage());
24                return null;
25            });
26}).toList();
27
28CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

This is useful for health dashboards and monitoring tools that check many services at once.

Common Pitfalls

A common mistake is calling this operation a “ping” and assuming it has network-level semantics. HTTP availability is an application-level check.

Another mistake is omitting timeouts and then wondering why health checks hang under failure conditions.

Developers also often treat every non-200 response as total outage, even when redirects or endpoint-specific status codes are acceptable.

Finally, do not send full expensive GET requests repeatedly if a simple header-level or lightweight availability check would do.

Summary

  • Use an HTTP client, not ICMP ping logic, to test HTTP URL availability.
  • Java 11 HttpClient is the preferred built-in API.
  • Define success policy explicitly in terms of status codes and timeouts.
  • Start with HEAD, with a fallback if the server does not support it.
  • Use async requests when checking many endpoints.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.