Java / Java 21 Interview Questions
What is the Java 11 HttpClient and how do you use it for HTTP requests?
The java.net.http.HttpClient (JEP 321, finalised in Java 11) is a modern, non-blocking HTTP client that supports HTTP/1.1 and HTTP/2, WebSockets, synchronous and asynchronous request modes, and streaming. It replaces the antiquated HttpURLConnection.
import java.net.http.*;
import java.net.URI;
import java.time.Duration;
// Build a reusable client (expensive to create — use as singleton)
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(10))
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
// Synchronous GET
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/users/1"))
.header("Accept", "application/json")
.timeout(Duration.ofSeconds(30))
.GET()
.build();
HttpResponse response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode()); // 200
System.out.println(response.body()); // JSON string
// Asynchronous POST with JSON body
HttpRequest postRequest = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/users"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("""
{"name":"Alice","age":30}
"""))
.build();
client.sendAsync(postRequest, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join(); // wait for demo purposes
// With virtual threads (Java 21): use send() (blocking) — no need for sendAsync()
// The virtual thread parks during the network wait — OS thread is free
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
