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.
| Modifier and Type | Class and Description |
|---|---|
| public static interface | HttpRequest.
A |
| public static class | HttpRequest.
Implementations of |
| public static interface | HttpRequest.
A builder of HTTP requests. |
| Access | Constructor and Description |
|---|---|
| protected |
| Modifier and Type | Method and Description |
|---|---|
| public abstract Optional | Returns: anOptional containing this request's BodyPublisherReturns an |
| public final boolean | Returns: true if, and only if, the given object is an HttpRequest that is equal to this HTTP requestthe object to which this object is to be compared obj)Overrides java. Tests this HTTP request instance for equality with the given object. |
| public abstract boolean | Returns: this request's expect continue settingReturns this request's expect continue setting. |
| public < the type of the option T> Optional | Returns: the value configured on this request for the given option, if anya request configuration option option)Returns the value configured on this request for the given option, if any. |
| public final int | Returns: the hash-code value for this HTTP requestOverrides java. Computes a hash code for this HTTP request instance. |
| public abstract HttpHeaders | Returns: this request's HttpHeadersThe (user-accessible) request headers that this request was (or will be) sent with. |
| public abstract String | |
| public static HttpRequest. | Returns: a new request builderthe request URI uri)Creates an |
| public static HttpRequest. | Returns: a new request builderthe original request request, BiPredicate<String, String> a header filter filter)Creates a |
| public static HttpRequest. | |
| public abstract Optional | Returns: anOptional containing this request's timeout durationReturns an |
| public abstract URI | |
| public abstract Optional | Returns: HTTP protocol versionReturns an |
| HttpRequest | back to summary |
|---|---|
| protected HttpRequest() Creates an HttpRequest. | |
| bodyPublisher | back to summary |
|---|---|
| public abstract Optional Returns an
| |
| equals | back to summary |
|---|---|
| public final boolean equals(Object obj) Overrides java. Tests this HTTP request instance for equality with the given object. If the given object is not an This method satisfies the general contract of the | |
| expectContinue | back to summary |
|---|---|
| public abstract boolean expectContinue() Returns this request's expect continue setting.
| |
| getOption | back to summary |
|---|---|
| public <T> Optional Returns the value configured on this request for the given option, if any. Implementation Specification The default implementation of this method returns
| |
| hashCode | back to summary |
|---|---|
| public final int hashCode() Overrides java. Computes a hash code for this HTTP request instance. The hash code is based upon the HTTP request's URI, method, and
header components, and satisfies the general contract of the
| |
| headers | back to summary |
|---|---|
| public abstract HttpHeaders headers() The (user-accessible) request headers that this request was (or will be) sent with.
| |
| method | back to summary |
|---|---|
| public abstract String method() Returns the request method for this request. If not set explicitly, the default method for any request is "GET".
| |
| newBuilder | back to summary |
|---|---|
| public static HttpRequest. Creates an
| |
| newBuilder | back to summary |
|---|---|
| public static HttpRequest. Creates a This builder can be used to build an The API Note The following scenarios demonstrate typical use-cases of the filter.
Given an
| |
| newBuilder | back to summary |
|---|---|
| public static HttpRequest. Creates an
| |
| timeout | back to summary |
|---|---|
| public abstract Optional Returns an | |
| uri | back to summary |
|---|---|
| public abstract URI uri() Returns this request's
| |
| version | back to summary |
|---|---|
| public abstract Optional Returns an
| |
BodyPublisher converts high-level Java objects into a flow of
byte buffers suitable for sending as a request body. The class
BodyPublishers provides implementations of many
common publishers.
The BodyPublisher interface extends Flow., which means that a BodyPublisher
acts as a publisher of byte buffers.
When sending a request that contains a body, the HTTP Client
subscribes to the request's BodyPublisher in order to receive the
flow of outgoing request body data. The normal semantics of Flow. and Flow. are implemented by the HTTP
Client and are expected from BodyPublisher implementations. Each
outgoing request results in one HTTP Client Subscriber
subscribing to the BodyPublisher in order to provide the sequence
of byte buffers containing the request body. Instances of ByteBuffer published by the publisher must be allocated by the
publisher, and must not be accessed after being published to the HTTP
Client. These subscriptions complete normally when the request body is
fully sent, and can be canceled or terminated early through error. If a
request needs to be resent for any reason, then a new subscription is
created which is expected to generate the same data as before.
A BodyPublisher that reports a content length of 0 may not be subscribed to by the HTTP Client,
as it has effectively no data to publish.
BodyPublishers
| Modifier and Type | Method and Description |
|---|---|
| public long | Returns: the content length for this request body, if knownReturns the content length for this request body. |
| contentLength | back to summary |
|---|---|
| public long contentLength() Returns the content length for this request body. May be zero if no request body being sent, greater than zero for a fixed length content, or less than zero for an unknown content length. This method may be invoked before the publisher is subscribed to. This method may be invoked more than once by the HTTP client implementation, and MUST return the same constant value each time.
| |
BodyPublisher that implement
various useful publishers, such as publishing the request body from a
String, or from a file.
The following are examples of using the predefined body publishers to convert common high-level Java objects into a flow of data suitable for sending as a request body:
// Request body from a String
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://foo.com/"))
.header("Content-Type", "text/plain; charset=UTF-8")
.POST(BodyPublishers.ofString("some body text"))
.build();
// Request body from a File
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://foo.com/"))
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofFile(Paths.get("file.json")))
.build();
// Request body from a byte array
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://foo.com/"))
.POST(BodyPublishers.ofByteArray(new byte[] { ... }))
.build();
| Access | Constructor and Description |
|---|---|
| private |
| Modifier and Type | Method and Description |
|---|---|
| public static HttpRequest. | Returns: An aggregate publisher that publishes a request body logically equivalent to the concatenation of all bytes published by each publisher in the sequence.a sequence of publishers. publishersReturns a |
| public static HttpRequest. | Returns: a BodyPublisherthe publisher responsible for publishing the body publisherReturns a request body publisher whose body is retrieved from the
given |
| public static HttpRequest. | Returns: a BodyPublisherthe publisher responsible for publishing the body publisher,a positive number representing the exact
amount of bytes the publisher will publish contentLength)Returns a request body publisher whose body is retrieved from the
given |
| public static HttpRequest. | Returns: a BodyPublisher which completes immediately and sends no request body.A request body publisher which sends no request body. |
| public static HttpRequest. | Returns: a BodyPublisherthe byte array containing the body buf)Returns a request body publisher whose body is the given byte array. |
| public static HttpRequest. | Returns: a BodyPublisherthe byte array containing the body buf, int the offset of the first byte offset, int the number of bytes to use length)Returns a request body publisher whose body is the content of the
given byte array of |
| public static HttpRequest. | Returns: a BodyPublisheran Iterable of byte arrays iter)A request body publisher that takes data from an |
| public static HttpRequest. | |
| public static HttpRequest. | Returns: a request body publisher whose body is thelength
content bytes read from the provided file channel starting
from the specified offseta file channel channel, long the offset of the first byte offset, long the number of bytes to read from the file channel length)Returns a request body publisher whose body is the |
| public static HttpRequest. | Returns: a BodyPublishera Supplier of open InputStreams streamSupplier)A request body publisher that reads its data from an |
| public static HttpRequest. | |
| public static HttpRequest. |
| BodyPublishers | back to summary |
|---|---|
| private BodyPublishers() | |
| concat | back to summary |
|---|---|
| public static HttpRequest. Returns a If the sequence is empty an empty publisher is returned. Otherwise, if the sequence contains a single element, that publisher is returned. Otherwise a concatenation publisher is returned. The request body published by a concatenation publisher is logically equivalent to the request body that would have been published by concatenating all the bytes of each publisher in sequence. Each publisher is lazily subscribed to in turn, until all the body bytes are published, an error occurs, or the concatenation publisher's subscription is cancelled. The concatenation publisher may be subscribed to more than once, which in turn may result in the publishers in the sequence being subscribed to more than once. The concatenation publisher has a known content
length only if all publishers in the sequence have a known content
length. The
Implementation Note If the concatenation publisher's subscription is cancelled, or an error occurs while publishing the bytes, not all publishers in the sequence may be subscribed to.
| |
| fromPublisher | back to summary |
|---|---|
| public static HttpRequest. Returns a request body publisher whose body is retrieved from the
given API Note This method can be used as an adapter between
| |
| fromPublisher | back to summary |
|---|---|
| public static HttpRequest. Returns a request body publisher whose body is retrieved from the
given The given API Note This method can be used as an adapter between
| |
| noBody | back to summary |
|---|---|
| public static HttpRequest. A request body publisher which sends no request body.
| |
| ofByteArray | back to summary |
|---|---|
| public static HttpRequest. Returns a request body publisher whose body is the given byte array.
| |
| ofByteArray | back to summary |
|---|---|
| public static HttpRequest. Returns a request body publisher whose body is the content of the
given byte array of
| |
| ofByteArrays | back to summary |
|---|---|
| public static HttpRequest. A request body publisher that takes data from an
| |
| ofFile | back to summary |
|---|---|
| public static HttpRequest. A request body publisher that takes data from the contents of a File.
| |
| ofFileChannel | back to summary |
|---|---|
| public static HttpRequest. Returns a request body publisher whose body is the
This method and the returned API Note This method can be used to either publish just a region of a file as
the request body or to publish different regions of a file
concurrently. A typical usage would be to publish different regions
of a file by creating a single instance of
| |
| ofInputStream | back to summary |
|---|---|
| public static HttpRequest. A request body publisher that reads its data from an
| |
| ofString | back to summary |
|---|---|
| public static HttpRequest. Returns a request body publisher whose body is the given
| |
| ofString | back to summary |
|---|---|
| public static HttpRequest. Returns a request body publisher whose body is the given
| |
Instances of HttpRequest.Builder are created by calling
HttpRequest#newBuilder(), HttpRequest#newBuilder(URI),
or HttpRequest#newBuilder(HttpRequest, BiPredicate).
The builder can be used to configure per-request state, such as: the
request URI, the request method (default is GET unless explicitly set),
specific request headers, etc. Each of the setter methods modifies the
state of the builder and returns the same instance. The methods are not
synchronized and should not be called from multiple threads without
external synchronization. The build method returns a new
HttpRequest each time it is invoked. Once built an HttpRequest is immutable, and can be sent multiple times.
Note, that not all request headers may be set by user code. Some are restricted for security reasons and others such as the headers relating to authentication, redirection and cookie management may be managed by specific APIs rather than through directly user set headers.
| Modifier and Type | Method and Description |
|---|---|
| public HttpRequest | |
| public HttpRequest. | Returns: an exact copy of this builderReturns an exact duplicate copy of this |
| public HttpRequest. | |
| public HttpRequest. | Returns: this buildertrue if Expect continue to be sentRequests the server to acknowledge the request before sending the body. |
| public HttpRequest. | |
| public default HttpRequest. | |
| public HttpRequest. | |
| public HttpRequest. | |
| public HttpRequest. | Returns: this builderthe method to use method, HttpRequest.the body publisher bodyPublisherSets the request method and request body of this builder to the given values. |
| public HttpRequest. | Returns: this builderthe body publisher bodyPublisherSets the request method of this builder to POST and sets its request body publisher to the given value. |
| public HttpRequest. | Returns: this builderthe body publisher bodyPublisherSets the request method of this builder to PUT and sets its request body publisher to the given value. |
| public HttpRequest. | |
| public default <T> HttpRequest. | Returns: this builderthe request configuration option option, T the request configuration option value (can be null) value)Provides request configuration option hints modeled as key value pairs
to help an |
| public HttpRequest. | |
| public HttpRequest. | |
| public HttpRequest. | Returns: this builderthe HTTP protocol version requested versionSets the preferred |
| build | back to summary |
|---|---|
| public HttpRequest build() Builds and returns an Implementation Specification This method returns a new
| |
| copy | back to summary |
|---|---|
| public HttpRequest. Returns an exact duplicate copy of this
| |
| DELETE | back to summary |
|---|---|
| public HttpRequest. Sets the request method of this builder to DELETE.
| |
| expectContinue | back to summary |
|---|---|
| public HttpRequest. Requests the server to acknowledge the request before sending the
body. This is disabled by default. If enabled, the server is
requested to send an error response or a
| |
| GET | back to summary |
|---|---|
| public HttpRequest. Sets the request method of this builder to GET. This is the default.
| |
| HEAD | back to summary |
|---|---|
| public default HttpRequest. Sets the request method of this builder to HEAD. Implementation Specification The default implementation is expected to have the same behaviour as:
| |
| header | back to summary |
|---|---|
| public HttpRequest. Adds the given name value pair to the set of headers for this request. The given value is added to the list of values for that name. Implementation Note An implementation may choose to restrict some header names
or values, as the HTTP Client may determine their value itself.
For example, "Content-Length", which will be determined by
the request Publisher. In such a case, an implementation of
| |
| headers | back to summary |
|---|---|
| public HttpRequest. Adds the given name value pairs to the set of headers for this
request. The supplied
| |
| method | back to summary |
|---|---|
| public HttpRequest. Sets the request method and request body of this builder to the given values. API Note The
| |
| POST | back to summary |
|---|---|
| public HttpRequest. Sets the request method of this builder to POST and sets its request body publisher to the given value.
| |
| PUT | back to summary |
|---|---|
| public HttpRequest. Sets the request method of this builder to PUT and sets its request body publisher to the given value.
| |
| setHeader | back to summary |
|---|---|
| public HttpRequest. Sets the given name value pair to the set of headers for this request. This overwrites any previously set values for name.
| |
| setOption | back to summary |
|---|---|
| public default <T> HttpRequest. Provides request configuration option hints modeled as key value pairs
to help an An
If this method is invoked twice for the same request option, any value previously provided to this builder for the
corresponding option is replaced by the new value.
If Implementation Specification The default implementation of this method discards the provided option hint and does nothing. Implementation Note The JDK built-in implementation of the
| |
| timeout | back to summary |
|---|---|
| public HttpRequest. Sets a timeout for this request. If the response is not received
within the specified timeout then an Implementation Specification A timeout applies to the duration measured from the instant the
request execution starts to, at least, the instant an
Implementation Note The JDK built-in implementation applies timeout over the duration measured from the instant the request execution starts to the instant the response body is consumed, if present. This is implemented by stopping the timer after the response body subscriber completion.
| |
| uri | back to summary |
|---|---|
| public HttpRequest. Sets this
| |
| version | back to summary |
|---|---|
| public HttpRequest. Sets the preferred The corresponding Implementation Note Constraints may also affect the selection of the actual protocol version.
| |