bhylu.com

Advertisements

Java Understand an HTTP Integration Boundary

An HTTP client exchanges data with another service. A URI, timeout and status policy are part of that integration, not incidental details to omit from an example.

Understand the idea

The JDK HttpClient API supports request construction and response handling. This self-contained lab starts a loopback-only HTTP server on an OS-assigned port, makes one request and stops the server. It does not contact an external website or provide a production server. Real integrations also need authentication, TLS verification, response-size limits, retry rules and safe handling of untrusted response data.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

import com.sun.net.httpserver.HttpServer;
import java.net.*;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

public class Main {
    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        server.createContext("/status", exchange -> {
            byte[] body = "ready".getBytes(StandardCharsets.UTF_8);
            exchange.sendResponseHeaders(200, body.length);
            try (var output = exchange.getResponseBody()) { output.write(body); }
        });
        server.start();
        try {
            URI address = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/status");
            HttpRequest request = HttpRequest.newBuilder(address).timeout(Duration.ofSeconds(3)).GET().build();
            try (HttpClient client = HttpClient.newHttpClient()) {
                HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
                System.out.println(response.statusCode() + ":" + response.body());
            }
        } finally {
            server.stop(0);
        }
    }
}

Expected output

200:ready

The OS selects a free port, so the example does not compete with Bhylu on port 8000. The address remains on loopback, and finally stops the local server. The output checks both status and body. Running this needs a local JDK that includes jdk.httpserver and permission to use a local loopback socket.

Check the official Java documentation for detailed contracts and supported options.