Package java.net.http

Class HttpRequest

java.lang.Object
java.net.http.HttpRequest

public abstract class HttpRequest extends Object
An HTTP request.

An HttpRequest instance is built through an HttpRequest builder. An HttpRequest builder is obtained from one of the newBuilder methods. A request's URI, headers, and body can be set. Request bodies are provided through a BodyPublisher supplied to one of the POST, PUT or method methods. Once all required parameters have been set in the builder, build will return the HttpRequest. Builders can be copied and modified many times in order to build multiple related requests that differ in some parameters.

The following is an example of a GET request that prints the response body as a String:

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
      .uri(URI.create("http://foo.com/"))
      .build();

client.sendAsync(request, BodyHandlers.ofString())
      .thenApply(HttpResponse::body)
      .thenAccept(System.out::println)
      .join();

The class BodyPublishers provides implementations of many common publishers. Alternatively, a custom BodyPublisher implementation can be used.

Since:
11