← Back to Advanced Java Course | Chapter 7: Networking & APIs | Lesson 3 of 4

Java HTTP Client

HttpClient Introduction

Java 11 introduced a modern HttpClient class built for today's web. It replaces the older, clunkier HttpURLConnection and supports both HTTP/1.1 and HTTP/2 seamlessly, including features like connection reuse and server push that the old API never handled well.

Example: HttpClient Introduction

java
import java.net.http.HttpClient;
public class Main {
	public static void main(String[] args) {
		HttpClient client = HttpClient.newHttpClient(); // supports HTTP/1.1 and HTTP/2
		System.out.println(client.version());
	}
}

HttpRequest and HttpResponse

You build outgoing requests using the fluent HttpRequest.Builder API and parse responses using BodyHandlers, such as ofString() for text or ofInputStream() for streaming large payloads. This builder pattern replaces the awkward, mutable connection objects the old HttpURLConnection API forced you to configure.

Example: HttpRequest and HttpResponse

java
import java.net.http.HttpRequest;
import java.net.URI;
public class Main {
	public static void main(String[] args) {
		HttpRequest request = HttpRequest.newBuilder()
			.uri(URI.create("https://example.com"))
			.build();
		System.out.println(request.method() + " " + request.uri());
	}
}

Asynchronous HTTP Requests

You can send HTTP requests asynchronously using sendAsync() instead of the blocking send(). This method returns a CompletableFuture immediately, letting your application continue other work while the network call completes in the background rather than freezing a thread on I/O.

Example: Asynchronous HTTP Requests

java
import java.util.concurrent.CompletableFuture;
public class Main {
	public static void main(String[] args) throws Exception {
		CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "response body"); // like sendAsync() returning immediately
		System.out.println(future.get());
	}
}

POST Requests with BodyPublishers

To send a POST request, use a BodyPublisher to define what goes in the request body -- for example, ofString() to send a JSON string directly, or ofFile() to stream a file's contents without loading it entirely into memory first.

Example: POST Requests with BodyPublishers

java
import java.net.http.HttpRequest;
import java.net.URI;
public class Main {
	public static void main(String[] args) {
		HttpRequest request = HttpRequest.newBuilder()
			.uri(URI.create("https://example.com/api"))
			.POST(HttpRequest.BodyPublishers.ofString("{\"key\":\"value\"}"))
			.build();
		System.out.println(request.method() + " body publisher attached");
	}
}

Managing Headers and Timeouts

You can add standard headers (like Content-Type or Authorization) directly on your request builder, and set connection or request timeouts to avoid a slow or unresponsive server hanging your application indefinitely.

Example: Managing Headers and Timeouts

java
import java.net.http.HttpRequest;
import java.net.URI;
import java.time.Duration;
public class Main {
	public static void main(String[] args) {
		HttpRequest request = HttpRequest.newBuilder()
			.uri(URI.create("https://example.com"))
			.header("Content-Type", "application/json")
			.timeout(Duration.ofSeconds(5))
			.build();
		System.out.println(request.headers().firstValue("Content-Type").get());
	}
}
🔒

Chapter Quiz — Complete all 4 topics to unlock

0/4 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.