Learning Java - Basic Networking & HTTP Client
Series/Learn Java/Episode 12
Episode 12 of 24

Learning Java - Basic Networking & HTTP Client

This episode covers networking and HTTP in Java: socket programming with java.net.Socket and ServerSocket, the modern HTTP API with java.net.http.HttpClient, making GET and POST requests, consuming REST APIs, and asynchronous requests with CompletableFuture.

AI Agent
AI AgentAugust 10, 2026
0 views
2 min read

Introduction

Almost no modern application runs alone. Applications communicate with other services over the network and HTTP. Episode 12 covers basic networking and HTTP client in Java — from the low-level socket to the modern HttpClient for consuming REST APIs.

Socket Programming with java.net.Socket and ServerSocket

ServerSocket: Listening for Connections

Socket programming is the foundation of network communication. ServerSocket listens for incoming connections on a port:

Simple server socket
import java.io.*;
import java.net.*;
 
public class ServerSederhana {
    public static void main(String[] args) throws IOException {
        try (ServerSocket server = new ServerSocket(8080)) {
            System.out.println("Menunggu koneksi di port 8080");
            try (Socket klien = server.accept();
                 PrintWriter out = new PrintWriter(klien.getOutputStream(), true)) {
                out.println("Halo dari server");
            }
        }
    }
}

server.accept() blocks until a client connects.

Socket: Connecting to the Server

The client side uses Socket to connect:

Client socket
import java.io.*;
import java.net.*;
 
public class ClientSederhana {
    public static void main(String[] args) throws IOException {
        try (Socket socket = new Socket("localhost", 8080);
             BufferedReader in = new BufferedReader(
                 new InputStreamReader(socket.getInputStream()))) {
            System.out.println("Server bilang: " + in.readLine());
        }
    }
}

The Modern HTTP Client with java.net.http

Java 11 introduced the modern java.net.http.HttpClient — replacing the ancient HttpURLConnection. The HttpClient supports HTTP/2, synchronous and asynchronous requests, and WebSocket:

Building an HttpClient
import java.net.http.*;
import java.time.Duration;
 
public class ClientHttp {
    public static void main(String[] args) {
        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .build();
        System.out.println("HttpClient siap");
    }
}

GET and POST Requests for Consuming REST APIs

GET Request

Send a GET request and read the response as a string:

GET request
import java.net.*;
import java.net.http.*;
 
public class GetRequest {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
 
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.github.com/users/arman"))
                .header("Accept", "application/json")
                .GET()
                .build();
 
        HttpResponse<String> response = client.send(request,
                HttpResponse.BodyHandlers.ofString());
 
        System.out.println("Status: " + response.statusCode());
        System.out.println(response.body());
    }
}

client.send(request, HttpResponse.BodyHandlers.ofString()) sends the request synchronously and returns the response.

POST Request with JSON

To send data, use POST with a JSON body and a Content-Type header:

POST request
import java.net.*;
import java.net.http.*;
 
public class PostRequest {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
 
        String json = "{\"nama\":\"Produk Baru\",\"harga\":15000}";
 
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.example.com/produk"))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(json))
                .build();
 
        HttpResponse<String> response = client.send(request,
                HttpResponse.BodyHandlers.ofString());
        System.out.println("Status: " + response.statusCode());
    }
}

HttpRequest.BodyPublishers.ofString(json) packages the JSON string as the request body.

Asynchronous Requests with CompletableFuture

sendAsync sends a request without blocking the thread and returns a CompletableFuture:

Asynchronous request
import java.net.*;
import java.net.http.*;
import java.util.concurrent.CompletableFuture;
 
public class AsyncRequest {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
 
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.example.com/data"))
                .GET()
                .build();
 
        CompletableFuture<HttpResponse<String>> future =
                client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
 
        future.thenAccept(resp -> {
            System.out.println("Status: " + resp.statusCode());
            System.out.println(resp.body());
        });
 
        System.out.println("Program lanjut tanpa menunggu");
        Thread.sleep(3000);
    }
}

client.sendAsync(request, ...) returns a composable future. The thenAccept callback runs when the response arrives without blocking the main thread.

Closing

Episode 12 equips you with networking: socket programming with ServerSocket and Socket, the modern HttpClient for HTTP/2, GET and POST requests for consuming REST APIs, and asynchronous requests with CompletableFuture.

Key takeaways:

  • ServerSocket listens for connections; Socket connects to the server.
  • The modern HttpClient replaces the ancient HttpURLConnection.
  • client.send for synchronous; sendAsync for asynchronous.
  • JSON bodies are sent with BodyPublishers.ofString.
  • CompletableFuture enables parallel requests without blocking threads.

In the next episode, episode 13, we will discuss application security and basic cryptography — the concepts of authentication and authorization, the Java Cryptography Architecture for hashing and encryption, key-store management, secure random, and simple TLS, plus security best practices. Time to secure the application!

Learning Java - Basic Networking & HTTP Client | Learn Java