Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

HttpRequest

An immutable HTTP request: address, method, headers and body. Created with newBuilder().

Available since: Java 11

Syntax

public abstract class HttpRequest

Examples

Building a GET request with a header and a timeout (no network needed for this):

import java.net.URI;
import java.net.http.HttpRequest;
 
void main() {
    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://api.example.com/users?page=2"))
        .header("Accept", "application/json")
        .timeout(Duration.ofSeconds(10))
        .GET()
        .build();
 
    IO.println(request.method());
    IO.println(request.uri());
    IO.println(request.headers().firstValue("Accept").orElse("-"));
}

Output:

GET
https://api.example.com/users?page=2
application/json

A POST with a JSON body. The local server sends back what it received:

import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.*;
 
void main() throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
    server.createContext("/users", exchange -> {
        String received = new String(exchange.getRequestBody().readAllBytes());
        String type = exchange.getRequestHeaders().getFirst("Content-Type");
        byte[] body = (exchange.getRequestMethod() + " " + type + " " + received).getBytes();
        exchange.sendResponseHeaders(201, body.length);
        exchange.getResponseBody().write(body);
        exchange.close();
    });
    server.start();
    URI uri = URI.create("http://localhost:" + server.getAddress().getPort() + "/users");
 
    String json = """
        {"name": "Anna", "age": 30}""";
    HttpRequest request = HttpRequest.newBuilder(uri)
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(json))
        .build();
 
    try (HttpClient client = HttpClient.newHttpClient()) {
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        IO.println(response.statusCode());
        IO.println(response.body());
    }
    server.stop(0);
}

Output:

201
POST application/json {"name": "Anna", "age": 30}

Notes

The default method is GET. Other methods: POST(body), PUT(body), DELETE() and the general method("PATCH", body). The body comes from BodyPublishers: ofString(), ofFile(path), ofByteArray(), noBody(). The Content-Type header is not set automatically — specify it explicitly. A request is immutable, so one object can be sent many times and from different threads.

See also

  • HttpClient — The built-in HTTP client: sends requests synchronously (send) or asynchronously (sendAsync).
  • HttpResponse — The server response: the status code, headers and a body of the type chosen by the BodyHandler.
  • Duration — An amount of time in seconds and nanoseconds — hours, minutes, seconds.

In the tutorial

  • HTTP client — Making requests to web servers from Java — HttpClient, HttpRequest and HttpResponse.BodyHandlers, GET and POST with JSON, status codes and asynchronous sendAsync.

Thanks for reading!

Donate to the site — we work hard for you.