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"));
}
}
Create a free account and build your private vault. Share publicly whenever you want.