Java 11 HTTP Client Tutorial 🎯

beginner
12 min

Java 11 HTTP Client Tutorial 🎯

Welcome to our comprehensive guide on using the Java 11 HTTP Client! In this lesson, we'll walk you through creating, sending, and receiving HTTP requests and responses using the new and improved Java 11 HTTP Client. By the end of this tutorial, you'll be able to make real-world applications that interact with APIs.

Why Java 11 HTTP Client? 💡

The Java 11 HTTP Client is an easy-to-use, modern, and powerful API for handling HTTP requests and responses. It replaces the old HttpURLConnection and simplifies the process of making network requests. This tutorial is designed for both beginners and intermediates, so let's get started!

Prerequisites 📝

To follow along with this tutorial, you'll need:

  • A text editor or Integrated Development Environment (IDE) like IntelliJ IDEA or Eclipse
  • Java 11 JDK installed on your system

Java 11 HTTP Client Basics 📝

Let's start by understanding the basic components of the Java 11 HTTP Client:

  1. HttpClient: This is the primary class for sending HTTP requests.
  2. HttpRequest: Represents an HTTP request with a specific method (e.g., GET, POST), URI, and headers.
  3. HttpResponse: Represents the response to an HTTP request, containing status code, headers, and the response body.

Making Your First HTTP Request 🎯

Now, let's make our first HTTP request using the Java 11 HTTP Client. We'll send a GET request to the JSONPlaceholder API to fetch a random quote.

java
import java.net.http.*; import java.util.concurrent.CompletableFuture; public class Main { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://jsonplaceholder.typicode.com/quotes/random")) .build(); CompletableFuture<HttpResponse<String>> responseFuture = client.sendAsync(request, HttpResponse.BodyHandlers.ofString()); HttpResponse<String> response = responseFuture.get(); System.out.println(response.body()); } }

In this example, we create an HttpClient instance, build an HttpRequest, and send it using the sendAsync() method. Finally, we print the response body.

Quick Quiz
Question 1 of 1

What does the `HttpResponse<String>` class represent in the Java 11 HTTP Client?

Extracting Data from the Response 📝

Now that we've made our first request, let's extract the data we need from the response.

java
import org.json.JSONObject; ... HttpResponse<String> response = responseFuture.get(); JSONObject jsonResponse = new JSONObject(response.body()); String quote = jsonResponse.getString("title"); System.out.println(quote);

Here, we use the JSONObject class from the org.json library to parse the JSON response and extract the quote's title.

Sending an HTTP Request with a Body 🎯

In addition to GET requests, we can also send POST requests with a body using the Java 11 HTTP Client. Let's send a simple POST request to create a new user in our API.

java
import java.net.http.*; import java.util.*; import java.util.concurrent.CompletableFuture; import org.json.JSONObject; public class Main { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://jsonplaceholder.typicode.com/users")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString("{\"name\": \"John\", \"username\": \"john_doe\", \"email\": \"john_doe@example.com\"}")) .build(); CompletableFuture<HttpResponse<String>> responseFuture = client.sendAsync(request, HttpResponse.BodyHandlers.ofString()); HttpResponse<String> response = responseFuture.get(); System.out.println(response.body()); } }

In this example, we set the request method to POST and provide a JSON string as the request body using the HttpRequest.BodyPublishers.ofString() method.

Summary 📝

Congratulations! You've learned the basics of using the Java 11 HTTP Client to make HTTP requests and handle responses. You've also learned how to extract data from JSON responses and send requests with a body. With this knowledge, you can start building powerful applications that interact with APIs.

Keep practicing and exploring the Java 11 HTTP Client to master its features and capabilities. Happy coding! 💡


I hope you found this tutorial helpful! If you have any questions or need further clarification, feel free to ask in the comments section below. Stay tuned for more Java tutorials here at CodeYourCraft! 🚀