Languages: Python C C++ Go Java Ruby Rust Perl R ← Full TOC

← Java Index

🌐 java.net — Networking — HTTP client, URL, sockets (Java 11+)

The modern java.net.http.HttpClient (Java 11+) provides a clean synchronous and asynchronous HTTP/2 client. The older java.net.URL class is still widely used for simple requests.

Import: import java.net.*; | Docs: Oracle JavaDoc

📋 Classes, Methods & Constants

NameSignatureDescription
HttpClientclass HttpClient (java.net.http)Modern HTTP/1.1 and HTTP/2 client (Java 11+)
HttpClient.newHttpClientstatic HttpClient newHttpClient()Create default HTTP client
HttpClient.newBuilderstatic Builder newBuilder()Build HTTP client with custom settings
HttpRequestclass HttpRequest (java.net.http)Immutable HTTP request
HttpRequest.newBuilderstatic Builder newBuilder(URI uri)Build HTTP request
request.GETBuilder GET()Set method to GET
request.POSTBuilder POST(BodyPublisher body)Set method to POST with body
BodyPublishers.ofStringstatic BodyPublisher ofString(String body)Create request body from string
HttpResponseclass HttpResponse<T> (java.net.http)HTTP response with body
response.statusCodeint statusCode()Return HTTP status code
response.bodyT body()Return response body
response.headersHttpHeaders headers()Return response headers
client.sendHttpResponse<T> send(HttpRequest req, BodyHandler<T> handler)Synchronous send
client.sendAsyncCompletableFuture<HttpResponse<T>> sendAsync(...)Asynchronous send
BodyHandlers.ofStringstatic BodyHandler<String> ofString()Receive body as String
URI.createstatic URI create(String str)Create URI from string
URLclass URL (java.net)Legacy URL class
url.openStreamInputStream openStream() throws IOExceptionOpen connection and return InputStream

💡 Example Program

Save as ClassName.java (matching the public class name), compile with javac ClassName.java, run with java ClassName.

import java.net.URI;
import java.net.http.*;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;

public class JavaNetDemo {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();

        // --- GET request ---
        HttpRequest getReq = HttpRequest.newBuilder()
            .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
            .header("Accept", "application/json")
            .GET()
            .build();

        HttpResponse<String> resp = client.send(getReq, BodyHandlers.ofString());
        System.out.println("Status : " + resp.statusCode());
        System.out.println("Body   : " + resp.body().substring(0, 120) + "...");

        // --- POST request ---
        String json = "{\"title\":\"Go Reference\",\"body\":\"MyWebUniversity\",\"userId\":1}";
        HttpRequest postReq = HttpRequest.newBuilder()
            .uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(json))
            .build();

        HttpResponse<String> postResp = client.send(postReq, BodyHandlers.ofString());
        System.out.println("\nPOST status: " + postResp.statusCode());
        System.out.println("POST body  : " + postResp.body());

        // --- Check response headers ---
        postResp.headers().map().forEach((k, v) ->
            System.out.printf("  Header: %-25s = %s%n", k, v));
    }
}
// javac JavaNetDemo.java && java JavaNetDemo
// (requires internet connection)

← java.util.stream  |  🏠 Index