Java

HttpClient — Synchronous GET (Java 11+)

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`java.net.http.HttpClient` ships in the JDK — no Apache HttpClient or OkHttp needed for most cases. Reuse one client across the app; configure timeouts and follow-redirects up front.
Java
Raw
import java.net.URI;
import java.net.http.*;
import java.time.Duration;

class Demo {
    // Reuse a single client — it's thread-safe and pools connections
    static final HttpClient client = HttpClient.newBuilder()
        .version(HttpClient.Version.HTTP_2)
        .followRedirects(HttpClient.Redirect.NORMAL)
        .connectTimeout(Duration.ofSeconds(5))
        .build();

    String fetch(String url) throws Exception {
        var req = HttpRequest.newBuilder()
            .GET()
            .uri(URI.create(url))
            .header("User-Agent", "myapp/1.0")
            .header("Accept",     "application/json")
            .timeout(Duration.ofSeconds(10))
            .build();

        HttpResponse<String> resp = client.send(req,
            HttpResponse.BodyHandlers.ofString());

        if (resp.statusCode() >= 400) {
            throw new RuntimeException("HTTP " + resp.statusCode());
        }
        return resp.body();
    }

    public static void main(String[] args) throws Exception {
        System.out.println(new Demo().fetch("https://api.github.com"));
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.