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

Java HTTP Client

HttpClient lets a Java program ask websites for information, like sending a request and reading the reply. It can also send data to a server.
Syntax
java
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("url"))
    .build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

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 so it can be used by its short name
import java.net.http.HttpRequest;
// Import java.net.URI so it can be used by its short name
import java.net.URI;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		HttpRequest request = HttpRequest.newBuilder()
			.uri(URI.create("https://example.com"))
			.build();
		// Print a line to the console
		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 so it can be used by its short name
import java.net.http.HttpRequest;
// Import java.net.URI so it can be used by its short name
import java.net.URI;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		HttpRequest request = HttpRequest.newBuilder()
			.uri(URI.create("https://example.com/api"))
			.POST(HttpRequest.BodyPublishers.ofString("{\"key\":\"value\"}"))
			.build();
		// Print a line to the console
		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 so it can be used by its short name
import java.net.http.HttpRequest;
// Import java.net.URI so it can be used by its short name
import java.net.URI;
import java.time.Duration;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	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();
		// Print a line to the console
		System.out.println(request.headers().firstValue("Content-Type").get());
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Assuming a 404 or 500 response throws an exception, when HttpClient returns it normally and you must check response.statusCode().
  2. Not setting a timeout on the request, so a slow server can block the program.
  3. Forgetting that sendAsync returns a CompletableFuture, so calling nothing like join() lets main finish before the response arrives.
🔒

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.