Advertisement

Java Networking & HTTP Client interview questions and answers

15 Java Networking & HTTP Client interview questions for Java roles, each with a model answer, examples and likely follow-ups.

15 questions
Advertisement

15 questions

Q11 Advanced Save

How would you implement connection-level HTTP/2 server push handling using HttpClient's PushPromiseHandler, and in what scenario would a server proactively push additional resources?

HTTP/2 server push lets a server proactively send additional resources to a client alongside a requested resource, anticipating the client will need them shortly (like pushing a CSS/JS file alongside the HTML page that references them, avoiding the client needing to make a separate subsequent request and round-trip for each one) -- HttpClient supports receiving these pushed resources via an optional PushPromiseHandler supplied to the send()/sendAsync() call, which receives a callback for each pushed resource with its own associated HttpRequest/HttpResponse pair, letting client code process pushed resources alongside the originally-requested one.
PushPromiseHandler<String> pushHandler = (initialRequest, pushPromiseRequest, acceptor) -> {
    CompletableFuture<HttpResponse<String>> pushedResponse =
        acceptor.apply(HttpResponse.BodyHandlers.ofString());
    pushedResponse.thenAccept(resp ->
        System.out.println("Received pushed resource: " + pushPromiseRequest.uri() + " -> " + resp.statusCode()));
};

client.sendAsync(request, HttpResponse.BodyHandlers.ofString(), pushHandler);
Real-world example
A web application server using HTTP/2 push proactively sends a page's associated CSS and JavaScript bundle alongside the initially requested HTML document, and a compatible HttpClient-based test tool verifies this push behavior works correctly by implementing a PushPromiseHandler that logs each received pushed resource.
Likely follow-ups
  • Why has HTTP/2 server push become less commonly used in practice despite its theoretical performance benefits, particularly for browser-based clients?
  • What happens if a server sends a pushed resource but the client's request doesn't include a PushPromiseHandler at all?
Diagnostics & Performance Hosting Models: Kestrel IIS & Reverse Proxies
Q12 Intermediate Save

How would you use InetAddress to perform DNS resolution (converting a hostname to an IP address) programmatically, and what's the difference between InetAddress.getByName() and getAllByName()?

InetAddress.getByName(hostname) resolves a hostname to a single IP address (returning the first one found if a hostname resolves to multiple addresses, common for load-balanced services), while getAllByName(hostname) returns an array of ALL IP addresses that hostname currently resolves to, useful for implementing custom client-side load balancing or failover logic across multiple backend IPs -- both perform an actual DNS lookup (a network operation, meaning it can throw UnknownHostException if resolution fails, and involves genuine latency, so results are often worth caching briefly rather than re-resolving on every single use).
try {
    InetAddress address = InetAddress.getByName("example.com");
    System.out.println(address.getHostAddress());  // e.g. "93.184.216.34"

    InetAddress[] allAddresses = InetAddress.getAllByName("example.com");
    for (InetAddress addr : allAddresses) {
        System.out.println(addr.getHostAddress());  // could print multiple IPs for a load-balanced service
    }
} catch (UnknownHostException e) {
    System.err.println("DNS resolution failed: " + e.getMessage());
}
Real-world example
A custom client-side load balancer resolves a service's hostname using getAllByName() to discover all currently-advertised backend IP addresses, implementing its own round-robin distribution logic across them rather than relying purely on DNS's own (often simplistic, single-IP-per-query) round-robin behavior.
Likely follow-ups
  • How does DNS caching (both at the OS level and within the JVM itself) affect how frequently a repeated getByName() call actually performs a fresh network lookup?
  • What's the security risk of DNS rebinding attacks, and how might an application need to defend against it?
Diagnostics & Performance Security Headers Antiforgery & CSRF Protection
Q13 Advanced Save

How would you implement a simple HTTP server (not just a client) using the lightweight com.sun.net.httpserver.HttpServer class bundled with the JDK, without a full framework like Spring?

com.sun.net.httpserver.HttpServer (available in the JDK itself, though technically part of an internal/unsupported-officially package historically, now more formally exposed) provides a minimal, dependency-free way to stand up a basic HTTP server for simple use cases (a local development mock server, a lightweight health-check endpoint, a simple internal admin tool) without pulling in a full web framework, by registering a HttpHandler for specific URL paths that receives the raw HttpExchange (giving access to the request and letting you write the response) -- while genuinely useful for its simplicity in narrow scenarios, it lacks the routing, middleware, and ecosystem support a full framework like Spring Boot or Javalin provides, making it unsuitable for anything beyond simple, low-traffic, internal-use cases.
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/health", exchange -> {
    String response = "OK";
    exchange.sendResponseHeaders(200, response.length());
    try (OutputStream os = exchange.getResponseBody()) {
        os.write(response.getBytes());
    }
});
server.setExecutor(Executors.newFixedThreadPool(4));
server.start();
Real-world example
A local development tool needing a simple mock HTTP endpoint for testing purposes (simulating a third-party API's responses) spins up a lightweight com.sun.net.httpserver.HttpServer instance directly, avoiding the overhead and configuration complexity of bringing in a full web framework dependency purely for this narrow, temporary testing need.
Likely follow-ups
  • What are the specific limitations of this built-in server that would make it unsuitable for a genuine production-facing API?
  • Why is this class historically considered part of an 'internal' JDK package, and how does that affect its long-term API stability guarantees?
Hosting Models: Kestrel IIS & Reverse Proxies Testing ASP.NET Core Applications
Q14 Intermediate Save

How does HttpClient handle automatic following of HTTP redirects (3xx responses), and how would you configure or disable this behavior?

HttpClient.Redirect (configured via HttpClient.newBuilder().followRedirects(policy)) controls redirect-following behavior, with options including NEVER (never automatically follow redirects, giving the caller full control to inspect and manually handle any 3xx response), ALWAYS (always follow redirects regardless of protocol scheme changes, including a potentially security-relevant HTTPS-to-HTTP downgrade), and NORMAL (the sensible default, following redirects except when a redirect would downgrade from HTTPS to plain HTTP, a specific protection against a common security concern) -- understanding and deliberately choosing the appropriate policy matters for both correctness (some APIs use redirects meaningfully) and security (blindly following all redirects unconditionally, including protocol downgrades, can expose sensitive data).
HttpClient client = HttpClient.newBuilder()
    .followRedirects(HttpClient.Redirect.NORMAL)  // follows redirects, but refuses HTTPS-to-HTTP downgrades
    .build();

// To manually inspect and control redirect handling instead:
HttpClient manualClient = HttpClient.newBuilder()
    .followRedirects(HttpClient.Redirect.NEVER)
    .build();
HttpResponse<String> response = manualClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 302) {
    String newLocation = response.headers().firstValue("Location").orElseThrow();
    // decide explicitly whether/how to follow this redirect
}
Real-world example
A security-conscious HTTP client integration deliberately uses the default NORMAL redirect policy (rather than ALWAYS) specifically to ensure a compromised or misconfigured server response can never silently downgrade a sensitive request from HTTPS to unencrypted HTTP through a crafted redirect chain.
Likely follow-ups
  • What specific security risk does an HTTPS-to-HTTP redirect downgrade actually create for a client following it automatically?
  • How would you detect and log every redirect a request goes through, for debugging or auditing purposes?
HTTPS Certificates & Transport Security Security Headers Antiforgery & CSRF Protection
Q15 Beginner Save

How would you add custom HTTP headers (like an Authorization bearer token) to an outgoing request using HttpRequest.Builder?

HttpRequest.Builder's header(name, value) method (called once per header, or headers(String...) for multiple at once) lets you attach any custom HTTP header to an outgoing request, commonly used for authentication (Authorization: Bearer token), content negotiation (Accept, Content-Type), or custom API-specific headers -- multiple calls to header() with the same name typically add multiple values for that header (following HTTP's own semantics for repeatable headers) rather than overwriting a previous value, an important distinction from some other HTTP client libraries' differing conventions.
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com/protected"))
    .header("Authorization", "Bearer " + accessToken)
    .header("Accept", "application/json")
    .GET()
    .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
Real-world example
An API client authenticating with a bearer token attaches it via the Authorization header on every outgoing request using HttpRequest.Builder's header() method, following the standard OAuth2 bearer token convention that the target API expects for authenticating each individual request.
Likely follow-ups
  • How would you set a default set of headers to apply to every request sent through a given HttpClient, without repeating them on each individual HttpRequest.Builder call?
  • What happens if you call header() twice with the same header name -- does the second call overwrite the first?
Authentication RESTful Web APIs & Controllers

Showing 11–15 of 15