HttpResponse<T>
public static class HttpResponse.BodyHandlers extends Object
BodyHandler
that implement various useful handlers, such as handling the response body as a String, or streaming the response body to a file. These implementations do not examine the status code, meaning the body is always accepted. They typically return an equivalently named BodySubscriber
. Alternatively, a custom handler can be used to examine the status code and headers, and return a different body subscriber, of the same type, as appropriate.
The following are examples of using the predefined body handlers to convert a flow of response body data into common high-level Java objects:
// Receives the response body as a String
HttpResponse<String> response = client
.send(request, BodyHandlers.ofString());
// Receives the response body as a file
HttpResponse<Path> response = client
.send(request, BodyHandlers.ofFile(Paths.get("example.html")));
// Receives the response body as an InputStream
HttpResponse<InputStream> response = client
.send(request, BodyHandlers.ofInputStream());
// Discards the response body
HttpResponse<Void> response = client
.send(request, BodyHandlers.discarding());
Modifier and Type | Method | Description |
---|---|---|
static <T> HttpResponse.BodyHandler |
buffering |
Returns a BodyHandler which, when invoked, returns a buffering BodySubscriber that buffers data before delivering it to the downstream subscriber. |
static HttpResponse.BodyHandler |
discarding() |
Returns a response body handler that discards the response body. |
static HttpResponse.BodyHandler |
fromLineSubscriber |
Returns a response body handler that returns a BodySubscriber <Void> obtained from BodySubscribers.fromLineSubscriber(subscriber, s -> null, charset, null) , with the given subscriber . |
static <S extends Flow.Subscriber<? super String>, |
fromLineSubscriber |
Returns a response body handler that returns a BodySubscriber <T> obtained from BodySubscribers.fromLineSubscriber(subscriber, finisher, charset, lineSeparator) , with the given subscriber , finisher function, and line separator. |
static HttpResponse.BodyHandler |
fromSubscriber |
Returns a response body handler that returns a BodySubscriber <Void> obtained from HttpResponse.BodySubscribers.fromSubscriber(Subscriber) , with the given subscriber . |
static <S extends Flow.Subscriber<? super List<ByteBuffer>>, |
fromSubscriber |
Returns a response body handler that returns a BodySubscriber <T> obtained from HttpResponse.BodySubscribers.fromSubscriber(Subscriber, Function) , with the given subscriber and finisher function. |
static HttpResponse.BodyHandler |
ofByteArray() |
Returns a BodyHandler<byte[]> that returns a BodySubscriber <byte[]> obtained from BodySubscribers.ofByteArray() . |
static HttpResponse.BodyHandler |
ofByteArrayConsumer |
Returns a BodyHandler<Void> that returns a BodySubscriber <Void> obtained from BodySubscribers.ofByteArrayConsumer(Consumer) . |
static HttpResponse.BodyHandler |
ofFile |
|
static HttpResponse.BodyHandler |
ofFile |
Returns a BodyHandler<Path> that returns a BodySubscriber <Path> obtained from BodySubscribers.ofFile(Path,OpenOption...) . |
static HttpResponse.BodyHandler |
ofFileDownload |
Returns a BodyHandler<Path> that returns a BodySubscriber <Path > where the download directory is specified, but the filename is obtained from the Content-Disposition response header. |
static HttpResponse.BodyHandler |
ofInputStream() |
Returns a BodyHandler<InputStream> that returns a BodySubscriber <InputStream> obtained from BodySubscribers.ofInputStream . |
static HttpResponse.BodyHandler |
ofLines() |
Returns a BodyHandler<Stream<String>> that returns a BodySubscriber <Stream<String>> obtained from BodySubscribers.ofLines(charset) . |
static HttpResponse.BodyHandler |
ofPublisher() |
Returns a BodyHandler<Publisher<List<ByteBuffer>>> that creates a BodySubscriber <Publisher<List<ByteBuffer>>> obtained from BodySubscribers.ofPublisher() . |
static HttpResponse.BodyHandler |
ofString() |
Returns a BodyHandler<String> that returns a BodySubscriber <String> obtained from BodySubscribers.ofString(Charset) . |
static HttpResponse.BodyHandler |
ofString |
Returns a BodyHandler<String> that returns a BodySubscriber <String> obtained from BodySubscribers.ofString(Charset) . |
static <U> HttpResponse.BodyHandler |
replacing |
Returns a response body handler that returns the given replacement value, after discarding the response body. |
public static HttpResponse.BodyHandler<Void> fromSubscriber(Flow.Subscriber<? super List<ByteBuffer>> subscriber)
BodySubscriber
<Void>
obtained from HttpResponse.BodySubscribers.fromSubscriber(Subscriber)
, with the given subscriber
. The response body is not available through this, or the
HttpResponse
API, but instead all response body is forwarded to the given subscriber
, which should make it available, if appropriate, through some other mechanism, e.g. an entry in a database, etc.
BodySubscriber
and Flow.Subscriber
. For example:
TextSubscriber subscriber = new TextSubscriber();
HttpResponse<Void> response = client.sendAsync(request,
BodyHandlers.fromSubscriber(subscriber)).join();
System.out.println(response.statusCode());
subscriber
- the subscriberpublic static <S extends Flow.Subscriber<? super List<ByteBuffer>>, T> HttpResponse.BodyHandler<T> fromSubscriber(S subscriber, Function<? super S,? extends T> finisher)
BodySubscriber
<T>
obtained from HttpResponse.BodySubscribers.fromSubscriber(Subscriber, Function)
, with the given subscriber
and finisher
function. The given finisher
function is applied after the given subscriber's onComplete
has been invoked. The finisher
function is invoked with the given subscriber, and returns a value that is set as the response's body.
BodySubscriber
and Flow.Subscriber
. For example:
TextSubscriber subscriber = ...; // accumulates bytes and transforms them into a String
HttpResponse<String> response = client.sendAsync(request,
BodyHandlers.fromSubscriber(subscriber, TextSubscriber::getTextResult)).join();
String text = response.body();
S
- the type of the SubscriberT
- the type of the response bodysubscriber
- the subscriberfinisher
- a function to be applied after the subscriber has completedpublic static HttpResponse.BodyHandler<Void> fromLineSubscriber(Flow.Subscriber<? super String> subscriber)
BodySubscriber
<Void>
obtained from BodySubscribers.fromLineSubscriber(subscriber, s -> null, charset, null)
, with the given subscriber
. The charset
used to decode the response body bytes is obtained from the HTTP response headers as specified by ofString()
, and lines are delimited in the manner of BufferedReader.readLine()
. The response body is not available through this, or the
HttpResponse
API, but instead all response body is forwarded to the given subscriber
, which should make it available, if appropriate, through some other mechanism, e.g. an entry in a database, etc.
BodySubscriber
and a text based Flow.Subscriber
that parses text line by line. For example:
// A PrintSubscriber that implements Flow.Subscriber<String>
// and print lines received by onNext() on System.out
PrintSubscriber subscriber = new PrintSubscriber(System.out);
client.sendAsync(request, BodyHandlers.fromLineSubscriber(subscriber))
.thenApply(HttpResponse::statusCode)
.thenAccept((status) -> {
if (status != 200) {
System.err.printf("ERROR: %d status received%n", status);
}
});
subscriber
- the subscriberpublic static <S extends Flow.Subscriber<? super String>, T> HttpResponse.BodyHandler<T> fromLineSubscriber(S subscriber, Function<? super S,? extends T> finisher, String lineSeparator)
BodySubscriber
<T>
obtained from BodySubscribers.fromLineSubscriber(subscriber, finisher, charset, lineSeparator)
, with the given subscriber
, finisher
function, and line separator. The charset
used to decode the response body bytes is obtained from the HTTP response headers as specified by ofString()
. The given finisher
function is applied after the given subscriber's onComplete
has been invoked. The finisher
function is invoked with the given subscriber, and returns a value that is set as the response's body.
BodySubscriber
and a text based Flow.Subscriber
that parses text line by line. For example:
// A LineParserSubscriber that implements Flow.Subscriber<String>
// and accumulates lines that match a particular pattern
Pattern pattern = ...;
LineParserSubscriber subscriber = new LineParserSubscriber(pattern);
HttpResponse<List<String>> response = client.send(request,
BodyHandlers.fromLineSubscriber(subscriber, s -> s.getMatchingLines(), "\n"));
if (response.statusCode() != 200) {
System.err.printf("ERROR: %d status received%n", response.statusCode());
}
S
- the type of the SubscriberT
- the type of the response bodysubscriber
- the subscriberfinisher
- a function to be applied after the subscriber has completedlineSeparator
- an optional line separator: can be null
, in which case lines will be delimited in the manner of BufferedReader.readLine()
.IllegalArgumentException
- if the supplied lineSeparator
is the empty stringpublic static HttpResponse.BodyHandler<Void> discarding()
public static <U> HttpResponse.BodyHandler<U> replacing(U value)
U
- the response body typevalue
- the value of U to return as the body, may be null
public static HttpResponse.BodyHandler<String> ofString(Charset charset)
BodyHandler<String>
that returns a BodySubscriber
<String>
obtained from BodySubscribers.ofString(Charset)
. The body is decoded using the given character set.charset
- the character set to convert the body withpublic static HttpResponse.BodyHandler<Path> ofFile(Path file, OpenOption... openOptions)
BodyHandler<Path>
that returns a BodySubscriber
<Path>
obtained from BodySubscribers.ofFile(Path,OpenOption...)
. When the HttpResponse
object is returned, the body has been completely written to the file, and HttpResponse.body()
returns a reference to its Path
.
In the case of the default file system provider, security manager permission checks are performed in this factory method, when the BodyHandler
is created. Otherwise, permission checks may be performed asynchronously against the caller's context at file access time. Care must be taken that the BodyHandler
is not shared with untrusted code.
file
- the file to store the body inopenOptions
- any options to use when opening/creating the fileIllegalArgumentException
- if an invalid set of open options are specifiedSecurityException
- in the case of the default file system provider, and a security manager is installed, checkWrite
is invoked to check write access to the given filepublic static HttpResponse.BodyHandler<Path> ofFile(Path file)
BodyHandler<Path>
that returns a BodySubscriber
<Path>
. Equivalent to: ofFile(file, CREATE, WRITE)
In the case of the default file system provider, security manager permission checks are performed in this factory method, when the BodyHandler
is created. Otherwise, permission checks may be performed asynchronously against the caller's context at file access time. Care must be taken that the BodyHandler
is not shared with untrusted code.
file
- the file to store the body inSecurityException
- in the case of the default file system provider, and a security manager is installed, checkWrite
is invoked to check write access to the given filepublic static HttpResponse.BodyHandler<Path> ofFileDownload(Path directory, OpenOption... openOptions)
BodyHandler<Path>
that returns a BodySubscriber
<Path
> where the download directory is specified, but the filename is obtained from the Content-Disposition
response header. The Content-Disposition
header must specify the attachment type and must also contain a filename parameter. If the filename specifies multiple path components only the final component is used as the filename (with the given directory name). When the HttpResponse
object is returned, the body has been completely written to the file and HttpResponse.body()
returns a Path
object for the file. The returned Path
is the combination of the supplied directory name and the file name supplied by the server. If the destination directory does not exist or cannot be written to, then the response will fail with an IOException
.
Security manager permission checks are performed in this factory method, when the BodyHandler
is created. Care must be taken that the BodyHandler
is not shared with untrusted code.
directory
- the directory to store the file inopenOptions
- open options used when opening the fileIllegalArgumentException
- if the given path does not exist, is not of the default file system, is not a directory, is not writable, or if an invalid set of open options are specifiedSecurityException
- in the case of the default file system provider and a security manager has been installed, and it denies read access to the directory, or it denies write access to the directory, or it denies write access to the files within the directory.public static HttpResponse.BodyHandler<InputStream> ofInputStream()
BodyHandler<InputStream>
that returns a BodySubscriber
<InputStream>
obtained from BodySubscribers.ofInputStream
. When the HttpResponse
object is returned, the response headers will have been completely read, but the body may not have been fully received yet. The HttpResponse.body()
method returns an InputStream
from which the body can be read as it is received.
HttpResponse.BodySubscribers.ofInputStream()
for more information.public static HttpResponse.BodyHandler<Stream<String>> ofLines()
BodyHandler<Stream<String>>
that returns a BodySubscriber
<Stream<String>>
obtained from BodySubscribers.ofLines(charset)
. The charset
used to decode the response body bytes is obtained from the HTTP response headers as specified by ofString()
, and lines are delimited in the manner of BufferedReader.readLine()
. When the HttpResponse
object is returned, the body may not have been completely received.
public static HttpResponse.BodyHandler<Void> ofByteArrayConsumer(Consumer<Optional<byte[]>> consumer)
BodyHandler<Void>
that returns a BodySubscriber
<Void>
obtained from BodySubscribers.ofByteArrayConsumer(Consumer)
. When the HttpResponse
object is returned, the body has been completely written to the consumer.
consumer
- a Consumer to accept the response bodypublic static HttpResponse.BodyHandler<byte[]> ofByteArray()
BodyHandler<byte[]>
that returns a BodySubscriber
<byte[]>
obtained from BodySubscribers.ofByteArray()
. When the HttpResponse
object is returned, the body has been completely written to the byte array.
public static HttpResponse.BodyHandler<String> ofString()
BodyHandler<String>
that returns a BodySubscriber
<String>
obtained from BodySubscribers.ofString(Charset)
. The body is decoded using the character set specified in the Content-Type
response header. If there is no such header, or the character set is not supported, then UTF_8
is used. When the HttpResponse
object is returned, the body has been completely written to the string.
public static HttpResponse.BodyHandler<Flow.Publisher<List<ByteBuffer>>> ofPublisher()
BodyHandler<Publisher<List<ByteBuffer>>>
that creates a BodySubscriber
<Publisher<List<ByteBuffer>>>
obtained from BodySubscribers.ofPublisher()
. When the HttpResponse
object is returned, the response headers will have been completely read, but the body may not have been fully received yet. The HttpResponse.body()
method returns a Publisher
<List<ByteBuffer>>
from which the body response bytes can be obtained as they are received. The publisher can and must be subscribed to only once.
HttpResponse.BodySubscribers.ofPublisher()
for more information.public static <T> HttpResponse.BodyHandler<T> buffering(HttpResponse.BodyHandler<T> downstreamHandler, int bufferSize)
BodyHandler
which, when invoked, returns a buffering BodySubscriber that buffers data before delivering it to the downstream subscriber. These BodySubscriber
instances are created by calling BodySubscribers.buffering
with a subscriber obtained from the given downstream handler and the bufferSize
parameter.T
- the response body typedownstreamHandler
- the downstream handlerbufferSize
- the buffer size parameter passed to BodySubscribers.buffering
IllegalArgumentException
- if bufferSize <= 0
© 1993, 2023, Oracle and/or its affiliates. All rights reserved.
Documentation extracted from Debian's OpenJDK Development Kit package.
Licensed under the GNU General Public License, version 2, with the Classpath Exception.
Various third party code in OpenJDK is licensed under different licenses (see Debian package).
Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
https://docs.oracle.com/en/java/javase/21/docs/api/java.net.http/java/net/http/HttpResponse.BodyHandlers.html